package com.mingqijia.gassafety.webserver.service.workorder.mbp;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.OperationLogVO;
import com.mingqijia.gassafety.db.entity.vo.UserServiceComboVO;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.request.ThreeQuotientCreateReq;
import com.mingqijia.gassafety.shared.response.ThreeQuotientAddOrderResp;
import com.mingqijia.gassafety.shared.response.ThreeQuotientByOrderIDListResp;
import com.mingqijia.gassafety.shared.service.ThreeQuotientService;
import com.mingqijia.gassafety.shared.user.UserBackend;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.BrowserNotifyReason;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkRecordsRequest;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkUpdateRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.OrgInfoRequest;
import com.mingqijia.gassafety.webserver.request.workorder.mbp.*;
import com.mingqijia.gassafety.webserver.request.workorder.order.OrderCreateDeviceList;
import com.mingqijia.gassafety.webserver.request.workorder.order.OrderCreateRequest;
import com.mingqijia.gassafety.webserver.response.HistoryAlarmAndBrokenResponse;
import com.mingqijia.gassafety.webserver.response.ConsoleSkNotifyAlarmResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsData;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkRecordsList;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUpdateResponse;

import com.mingqijia.gassafety.webserver.response.workorder.asst.AsstOrderListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.asst.OrgInfoResponse;
import com.mingqijia.gassafety.webserver.response.workorder.asst.WorkingOrderListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.AppealHistoryResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.HistoryListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.MbpOrderListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.workorder.AsstWorkOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.SkWorkOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import com.mingqijia.gassafety.webserver.webSocket.WebSocketProcess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单记录表 服务类
 * </p>
 *
 * @author guoliang.lao
 * @since 2022-11-16
 */
@Component
@Slf4j
public class MbpWorkOrderService {
    @Autowired
    WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    CompanyService companyService;
    @Autowired
    HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    HistoryBrokenMapper historyBrokenMapper;
    @Autowired
    AppealHistoryMapper appealHistoryMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    private DeviceStateMapper deviceStateMapper;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    TcisService tcisService;
    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    ConfigureHolder holder;
    @Value("${mbp.test.env}")
    String mbpTestEnv;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    SmartKitchenLogService kitchenLogService;
    @Autowired
    ConsoleSkFeignClient client;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;
    @Autowired
    AppealLogMapper appealLogMapper;
    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    WorkOrderHistoryMapper workOrderHistoryMapper;

    @Autowired
    AsstWorkOrderService asstWorkOrderService;

    @Autowired
    ConsoleSkAlarmService consoleSkAlarmService;

    @Autowired
    FieldTemplateService fieldTemplateService;

    @Autowired
    WarningAlarmMapper warningAlarmMapper;

    @Autowired
    SkWorkOrderService skWorkOrderService;

    @Autowired
    ServiceComboDetailService serviceComboDetailService;

    @Autowired
    WebSocketProcess webSocketProcess;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    ThreeQuotientService threeQuotientService;


    private final static String split_m = ":";

    @Value(value = "${asst.workOrder.aqLineBizCde:AQ0001}")
    private String aqLineBizCde;

    @Value(value = "${asst.workOrder.sosBizCde:SO0006}")
    private String sosBizCode;

    @Value(value = "${asst.workOrder.alarmBizCde:SO0005}")
    private String alarmBizCode;

    @Value(value = "${asst.workOrder.maintainBizCde:SO0003}")
    private String maintainBizCode;

    @Value(value = "${asst.workOrder.installBizCde:SO0002}")
    private String installBizCode;

    /**
     * 查询历史工单
     *
     * @param imei
     * @param page
     * @param pageSize
     * @return
     */
    public PageUtil<HistoryListResponse> historyList(String imei, Integer page, Integer pageSize) {
        List<HistoryListResponse> resultList = new ArrayList<>();
        String spId = ApplicationUtils.getWorkingSpId();

        if (imei.contains("-")) imei = imei.split("-")[0];
        LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(WorkOrderHistory::getDeviceId, imei).eq(WorkOrderHistory::getIsDeleted, 0)
                .eq(WorkOrderHistory::getSpId, spId)
                .orderByDesc(WorkOrderHistory::getCreatedAt);

        Page<WorkOrderHistory> pages = PageHelper.startPage(page, pageSize);
        List<WorkOrderHistory> list = workOrderHistoryService.list(queryWrapper);
        log.info("historyList-list:{}", JSONObject.toJSONString(list));
        if (!CollectionUtils.isEmpty(list)) {
            List<String> mbpOrderNos = new ArrayList<>();
            List<String> asstOrderNos = new ArrayList<>();
            List<String> sanShangOrderNos = new ArrayList<>();
            for (WorkOrderHistory workOrderHistory : list) {
                if (null!=workOrderHistory.getWorkSystem() && workOrderHistory.getWorkSystem()==4){
                    sanShangOrderNos.add(workOrderHistory.getOrderNo());
                }else if (null!=workOrderHistory.getWorkSystem() &&
                        (workOrderHistory.getWorkSystem()==0 || workOrderHistory.getWorkSystem()==2)){
                    asstOrderNos.add(workOrderHistory.getOrderNo());
                }else{
                    mbpOrderNos.add(workOrderHistory.getOrderNo());
                }
            }
            Map<String,MbpOrderListResponse> mbpOrderMap = new HashMap<>();
            if (!mbpOrderNos.isEmpty()) {
                List<MbpOrderListResponse> orderList = getOrderList(mbpOrderNos);
                log.info("mbpHistoryList-orderList:{}", JSONObject.toJSONString(orderList));
                mbpOrderMap = orderList.stream()
                        .collect(Collectors.toMap(MbpOrderListResponse::getOrderNo, Function.identity()));

            }
            Map<String,AsstOrderListResponse> asstOrderMap = new HashMap<>();
            if (!asstOrderNos.isEmpty()) {
                asstOrderMap = asstWorkOrderService.getOrdersMap(asstOrderNos,Arrays.asList(spId));
                log.info("asstHistoryList-orderList:{}", JSONObject.toJSONString(asstOrderMap));
            }
            Map<String, ThreeQuotientByOrderIDListResp> sanShangOrderMap = new HashMap<>();
            if (!sanShangOrderNos.isEmpty()) {
                sanShangOrderMap = threeQuotientService.queryOrderList(sanShangOrderNos);
            }
            for (WorkOrderHistory history : list) {
                HistoryListResponse res = new HistoryListResponse();
                if (mbpOrderMap.containsKey(history.getOrderNo()) && null!=mbpOrderMap.get(history.getOrderNo())) {
                    MbpOrderListResponse mbpOrderListResponse = mbpOrderMap.get(history.getOrderNo());
                    BeanUtils.copyProperties(mbpOrderListResponse, res);
                    res.setCreateTime(mbpOrderListResponse.getCreateTime());
                    res.setWorkSystemStr("时刻助手");
                    res.setSendTime(DateUtil.parse(mbpOrderListResponse.getCreateTime()));
                    res.setCompleteResultStr(MbpStateEnum.getStateName(mbpOrderListResponse.getOrderStatus()));
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setFromSystemStr("报警器");
                    res.setOperatorBy(history.getOperatorBy());
                    res.setSubsCode(history.getSubsCode());
                    res.setOrderType(history.getOrderChannel()==0?"外购销售单":"内购销售单");
                    resultList.add(res);
                }else if (asstOrderMap.containsKey(history.getOrderNo()) && null!=asstOrderMap.get(history.getOrderNo())) {
                    AsstOrderListResponse asstOrderListResponse = asstOrderMap.get(history.getOrderNo());
                    BeanUtils.copyProperties(asstOrderListResponse, res);
                    res.setSendTime(history.getCreatedAt());
                    res.setWorkSystemStr("时刻助手");
                    if (StringUtils.isEmpty(res.getOperatorBy())) {
                        res.setOperatorBy(history.getOperatorBy());
                    }
                    //时刻家发起的创建时间取工单创建时间
                    if (history.getWorkSystem().equals(AsstConstants.FROM_SYSTEM_1)) {
                        res.setCreateTime(DateUtils.format(asstOrderListResponse.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                    } else {
                        //报警器发起的创建时间取history表的创建时间
                        res.setCreateTime(DateUtils.format(history.getCreatedAt(),"yyyy-MM-dd HH:mm:ss"));
                    }
                    resultList.add(res);
                } else if (sanShangOrderMap.containsKey(history.getOrderNo()) && null!=sanShangOrderMap.get(history.getOrderNo())){
                    ThreeQuotientByOrderIDListResp threeQuotientByOrderIDListResp = sanShangOrderMap.get(history.getOrderNo());
                    res.setOrderNo(StringUtils.isEmpty(history.getPkid()) ? history.getOrderNo() : history.getPkid());
                    res.setCreateTime(DateUtils.format(history.getCreatedAt(),"yyyy-MM-dd HH:mm:ss"));
                    res.setCompletedTime(StringUtils.replace(threeQuotientByOrderIDListResp.getLastProcessDate(), "T", " "));
                    res.setWorkSystemStr("智能管网");
                    res.setSendTime(history.getCreatedAt());
                    res.setCompleteResultStr(ThreeQuotientStatEnum.getStateName(threeQuotientByOrderIDListResp.getStatus()));
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setFromSystemStr("报警器");
                    res.setOperatorBy(history.getOperatorBy());
                    res.setServicerName(threeQuotientByOrderIDListResp.getLastProcesser());
                    res.setSubsCode(history.getSubsCode());
                    resultList.add(res);
                }
            }
        }
        PageUtil pageInfo = new PageUtil<>(page, pageSize, pages.getTotal(), resultList);
        return pageInfo;
    }

    /**
     * 查询进行中的工单
     *
     * @param imei
     * @param page
     * @param pageSize
     * @return
     */
    public PageUtil<WorkingOrderListResponse> workingOrderList(String imei, Integer page, Integer pageSize) {
        List<WorkingOrderListResponse> resultList = new ArrayList<>();
        String spId = ApplicationUtils.getWorkingSpId();
        if (imei.contains("-")) imei = imei.split("-")[0];
        LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(WorkOrderHistory::getDeviceId, imei).eq(WorkOrderHistory::getIsDeleted, 0)
                .eq(WorkOrderHistory::getSpId, spId).eq(WorkOrderHistory::getHandleStatus, 0)
                .eq(WorkOrderHistory::getHandleStatus, 0)
                .orderByDesc(WorkOrderHistory::getCreatedAt);
        Page<HistoryAlarmVo> pages = PageHelper.startPage(page, pageSize);
        List<WorkOrderHistory> list = workOrderHistoryService.list(queryWrapper);
        log.info("workingOrderList-list:{}", JSONObject.toJSONString(list));
        if (null!=list && !list.isEmpty()) {
            List<String> mbpOrderNos = new ArrayList<>();
            List<String> asstOrderNos = new ArrayList<>();
            List<String> sanShangOrderNos = new ArrayList<>();
            for (WorkOrderHistory workOrderHistory : list) {
                if (null != workOrderHistory.getWorkSystem() && workOrderHistory.getWorkSystem() == 4) {
                    sanShangOrderNos.add(workOrderHistory.getOrderNo());
                } else if (null != workOrderHistory.getWorkSystem() &&
                        (workOrderHistory.getWorkSystem() == 0 || workOrderHistory.getWorkSystem() == 2)) {
                    asstOrderNos.add(workOrderHistory.getOrderNo());
                } else {
                    mbpOrderNos.add(workOrderHistory.getOrderNo());
                }
            }
            Map<String, MbpOrderListResponse> mbpOrderMap = new HashMap<>();
            if (!mbpOrderNos.isEmpty()) {
                List<MbpOrderListResponse> orderList = getOrderList(mbpOrderNos);
                log.info("mbpHistoryList-orderList:{}", JSONObject.toJSONString(orderList));
                mbpOrderMap = orderList.stream()
                        .collect(Collectors.toMap(MbpOrderListResponse::getOrderNo, Function.identity()));

            }
            Map<String, AsstOrderListResponse> asstOrderMap = new HashMap<>();
            if (!asstOrderNos.isEmpty()) {
                asstOrderMap = asstWorkOrderService.getOrdersMap(asstOrderNos, Arrays.asList(spId));
                log.info("asstHistoryList-orderList:{}", JSONObject.toJSONString(asstOrderMap));
            }
            Map<String, ThreeQuotientByOrderIDListResp> sanShangOrderMap = new HashMap<>();
            if (!sanShangOrderNos.isEmpty()) {
                sanShangOrderMap = threeQuotientService.queryOrderList(sanShangOrderNos);
            }
            for (WorkOrderHistory history : list) {
                WorkingOrderListResponse res = new WorkingOrderListResponse();
                if (mbpOrderMap.containsKey(history.getOrderNo()) && null != mbpOrderMap.get(history.getOrderNo())) {
                    MbpOrderListResponse mbpOrderListResponse = mbpOrderMap.get(history.getOrderNo());
                    BeanUtils.copyProperties(mbpOrderListResponse, res);
                    res.setSendTime(history.getCreatedAt());
                    res.setEquipmentStatus(history.getDeviceStatus());
                    res.setReason(history.getReason());
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setBookTime(mbpOrderListResponse.getBooktime());
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    if (history.getConcentration() != null) {
                        res.setXlel(history.getConcentration() + " %LEL");
                    } else {
                        res.setXlel("0% LEL");
                    }
                    res.setImei(imei);
                    resultList.add(res);
                } else if (asstOrderMap.containsKey(history.getOrderNo()) && null != asstOrderMap.get(history.getOrderNo())) {
                    AsstOrderListResponse asstOrderListResponse = asstOrderMap.get(history.getOrderNo());
                    BeanUtils.copyProperties(asstOrderListResponse, res);
                    res.setSendTime(history.getCreatedAt());
                    res.setEquipmentStatus(history.getDeviceStatus());
                    res.setReason(history.getReason());
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setBookTime(asstOrderListResponse.getBookTime());
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    if (history.getConcentration() != null) {
                        res.setXlel(history.getConcentration() + " %LEL");
                    } else {
                        res.setXlel("0% LEL");
                    }
                    res.setImei(imei);
                    resultList.add(res);
                } else if (sanShangOrderMap.containsKey(history.getOrderNo()) && null != sanShangOrderMap.get(history.getOrderNo())) {
                    ThreeQuotientByOrderIDListResp threeQuotientByOrderIDListResp = sanShangOrderMap.get(history.getOrderNo());
                    res.setOrderNo(StringUtils.isEmpty(history.getPkid()) ? history.getOrderNo() : history.getPkid());
                    res.setSendTime(history.getCreatedAt());
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setServicerName(threeQuotientByOrderIDListResp.getLastProcesser());
                    res.setEquipmentStatus(history.getDeviceStatus());
                    res.setReason(history.getReason());
                    res.setBizName(BizTypeEnum.getStateName(history.getOrderType() + ""));
                    res.setBookTime(threeQuotientByOrderIDListResp.getRepairDateTime());
                    res.setOrderStatusRemark(history.getHandleStatus() == 0 ? "进行中" : "完成");
                    if (history.getConcentration() != null) {
                        res.setXlel(history.getConcentration() + " %LEL");
                    } else {
                        res.setXlel("0% LEL");
                    }
                    res.setImei(imei);
                    resultList.add(res);
                }
            }
        }
        PageUtil pageInfo = new PageUtil<>(page, pageSize, pages.getTotal(), resultList);
        return pageInfo;
    }


    /**
     * 模板一, 发起安装工单
     *
     * @param request
     */
    public void initiateWorkOrder(InitiateWorkOrderRequest request) {


        String spId = ApplicationUtils.getWorkingSpId();
        workOrderHistoryService.existWorkOrder(request.getSubsCode(),spId);
        String orgCode = companyService.getOrgCode(spId,request.getSubsCode());
        String nowDate = DateUtil.format(DateUtil.date(), "yyyy-MM-dd"); //当前日期

        //查询户号信息
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        List<Consumer> consumers = consumerMapper.selectList(consumerQueryWrapper);

        //企业操作日志
        LogVO vo = new LogVO();

        if (CollectionUtil.isEmpty(consumers)) {
            vo.setDetail("户号不存在");
            LogRecordAspect.threadLocal.set(vo);
            throw new BizException("户号:" + request.getSubsCode() + "不存在");
        }
        Consumer consumer = consumers.get(0);
        vo.setDetail("【客户ID:" + consumer.getId() + "】");
        vo.setCommonInfo(LogUtil.addOrDeleteEntity(consumer, Consumer.class));
        LogRecordAspect.threadLocal.set(vo);

        if (consumer.getStatus()==1)  throw new BizException("工单进行中，客户信息不可修改");
        consumer.setStatus(1);
        log.info("initiateWorkOrder-consumer:{}",JSONObject.toJSON(consumer));
        consumerService.updateById(consumer);
        //判断客户是否已存在 正在进行中的诉求
        QueryWrapper<AppealHistory> appealHistoryQueryWrapper = new QueryWrapper<>();
        appealHistoryQueryWrapper.lambda().eq(AppealHistory::getSubsCode, request.getSubsCode())
                .eq(AppealHistory::getStatus, MbpConst.APPEAL_STATUS_ONGOING)  //进行中
                .eq(AppealHistory::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<AppealHistory> historyList = appealHistoryMapper.selectList(appealHistoryQueryWrapper);
        if (CollectionUtil.isNotEmpty(historyList)) {
            log.info("进行中的诉求信息:{}", JSONObject.toJSONString(historyList));
            throw new BizException("该客户存在未受理诉求,请稍后发起");
        }
        QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                .eq(FieldTemplate::getTemplateType, 1)
                .eq(FieldTemplate::getIsDeleted, 0);
        FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
        if (fieldTemplate.getWorkSystemType() == 2) {
            request.setMemberId(consumer.getMemberId());
            request.setConsumerId(consumer.getId());
            if (consumer.getPositionLat() != null) {
                request.setLat(String.valueOf(consumer.getPositionLat()));
            }
            if (consumer.getPositionLon() != null) {
                request.setLon(String.valueOf(consumer.getPositionLon()));
            }
            request.setAddress(consumer.getAddress());
            createNewInstallOrder(request);
            //操作日志log
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_3.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.t_gss_appeal_history.name());
            operationLogService.insertLog(logVO);
        } else {
            // 调用 5016 工商户用气设备 接口
            GsApplianceRequest applianceRequest = new GsApplianceRequest();
            applianceRequest.setUserid(request.getSubsCode());
            applianceRequest.setAppsource("1"); //报装
            applianceRequest.setRestype("BJ");
            applianceRequest.setIsuse("1");   // 是
            applianceRequest.setIsbuy(request.getIsbuy());
            applianceRequest.setFixposi("1");  //室内
            applianceRequest.setBuyaddr(request.getBuyaddr());
            applianceRequest.setBuydate(nowDate);
            applianceRequest.setBrand(request.getFactory());
            applianceRequest.setModelid(request.getBrand());
            ArrayList<GsApplianceRequest> applianceRequests = new ArrayList<>();
            applianceRequests.add(applianceRequest);
            Map<String, Object> applianceRequestMap = new HashMap<>();
            applianceRequestMap.put("body", applianceRequests);
            log.info(" 调用 5016 工商户用气设备");
            Map<String, Object> applianceResponseMap = tcisService.tcisRequest(applianceRequestMap, 0, null,request.getSubsCode());
            Integer code1 = (Integer) applianceResponseMap.get("code");
            // 5016接口结束, 诉求表新增记录;
            AppealHistory appealHistory = new AppealHistory();
            appealHistory.setAppealContent(JSONObject.toJSONString(request));
            appealHistory.setConsumerId(consumer.getId());
            appealHistory.setSubsCode(consumer.getSubsCode());
            appealHistory.setCustName(consumer.getCustName());
            appealHistory.setCustAddress(consumer.getCustAddress());
            appealHistory.setSpId(spId);
            if (code1.equals(0)) {
                appealHistory.setStatus(MbpConst.APPEAL_STATUS_ONGOING);  //进行中
                appealHistoryMapper.insert(appealHistory);

            } else {
                appealHistory.setStatus(MbpConst.APPEAL_STATUS_FAIL);
                appealHistory.setRemark("接口调用失败");
                appealHistoryMapper.insert(appealHistory);
                throw new BizException("诉求发起失败");
            }

            //调用 1022接口, 根据户号查询 外购燃气具信息, 此处pkid为销售单id
            String pkid = queryAlarmAppliance(request.getSubsCode(), appealHistory.getId());

            //调用3012接口,受理诉求, 发起安装
            String orderNo = outhouseInstall(request, orgCode, pkid);
            //诉求受理,更新状态
            AppealHistory appealHistory2 = new AppealHistory();
            appealHistory2.setId(appealHistory.getId());
            appealHistory2.setStatus(MbpConst.APPEAL_STATUS_SUCCESS);
            appealHistory2.setOrderNo(orderNo);
            appealHistoryMapper.updateById(appealHistory2);
            //新增工单历史, 状态,进行中
            insertWorkOrderHistory(request.getSubsCode(), spId, pkid, orderNo, request.getOrderCustType());

            //操作日志log
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_3.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.t_gss_appeal_history.name());
            logVO.setTableKey(appealHistory.getId().toString());
            operationLogService.insertLog(logVO);
        }


    }

    public String getPkid(InitiateWorkOrderRequest request, String spId) {
        // 调用 5016 工商户用气设备 接口
        GsApplianceRequest applianceRequest = new GsApplianceRequest();
        applianceRequest.setUserid(request.getSubsCode());
        applianceRequest.setAppsource("1"); //报装
        applianceRequest.setRestype("BJ");
        applianceRequest.setIsuse("1");   // 是
        applianceRequest.setIsbuy(request.getIsbuy());
        applianceRequest.setFixposi("1");  //室内
        applianceRequest.setBuyaddr(request.getBuyaddr());
        applianceRequest.setBuydate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd"));
        applianceRequest.setBrand(request.getFactory());
        applianceRequest.setModelid(request.getBrand());
        ArrayList<GsApplianceRequest> applianceRequests = new ArrayList<>();
        applianceRequests.add(applianceRequest);
        Map<String, Object> applianceRequestMap = new HashMap<>();
        applianceRequestMap.put("body", applianceRequests);
        log.info("调用 5016 工商户用气设备");
        Map<String, Object> applianceResponseMap = tcisService.tcisRequest(applianceRequestMap, 0, null,request.getSubsCode());
        Integer code1 = (Integer) applianceResponseMap.get("code");
        if (!code1.equals(0)) {
            throw new BizException("诉求发起失败");
        }

        //调用 1022接口, 根据户号查询 外购燃气具信息, 此处pkid为销售单id
        String pkid = getPkid(request.getSubsCode(), spId);
        return pkid;
    }

    /**
     * 更新指定 诉求的状态
     *
     * @param request
     */
    public void updateAppealStatus(AppealHistoryRequest request) {
        //根据诉求单id+户号为key;
        String key = request.getId().toString() + request.getSubsCode();
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.APPEAL_TIME_OUT);//5分钟超时
            if (acquire) {
                try {
                    String spId = ApplicationUtils.getWorkingSpId();
                    String orgCode = companyService.getOrgCode(spId,request.getSubsCode());
                    //根据诉求id 获取户号, 查询 1022
                    QueryWrapper<AppealHistory> historyQueryWrapper = new QueryWrapper<>();
                    historyQueryWrapper.lambda().eq(AppealHistory::getId, request.getId())
                            .eq(AppealHistory::getIsDeleted, Constants.IS_DELETED_FALSE)
                            .eq(AppealHistory::getSpId, spId);
                    List<AppealHistory> historyList = appealHistoryMapper.selectList(historyQueryWrapper);
                    AppealHistory appealHistory = historyList.get(0);
                    InitiateWorkOrderRequest historyRequest = JSON.parseObject(appealHistory.getAppealContent(), InitiateWorkOrderRequest.class);
                    // 1022
                    log.info("户号:{},诉求id:{}进行诉求单状态更新", appealHistory.getSubsCode(), appealHistory.getId());
                    String pkid = queryAlarmAppliance(appealHistory.getSubsCode(), appealHistory.getId());
                    //不允许 同一个销售单id发起多个安装单;
                    QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(WorkOrderHistory::getPkid, pkid)
                            .eq(WorkOrderHistory::getIsDeleted, Constants.IS_DELETED_FALSE);
                    List<WorkOrderHistory> histories = workOrderHistoryService.list(queryWrapper);
                    if (CollectionUtil.isNotEmpty(histories)) throw new BizException("同一pkid:" + pkid + "不允许多次创建安装单");

                    //3012
                    String orderNo = outhouseInstall(historyRequest, orgCode, pkid);

                    //诉求受理,更新状态
                    AppealHistory appealHistory2 = new AppealHistory();
                    appealHistory2.setId(appealHistory.getId());
                    appealHistory2.setStatus(MbpConst.APPEAL_STATUS_SUCCESS);
                    appealHistoryMapper.updateById(appealHistory2);
                    //新增工单历史, 状态,进行中
                    //查询户号信息
                    QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
                    consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                            .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                            .eq(Consumer::getSpId, spId);
                   Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
                    int orderCustType = 0;
                    if (null != consumer && !ObjectUtils.isEmpty(consumer)) {
                        orderCustType = Constants.ORDER_CUST_TYPE_COMPANY;
                        if (CustTypeEnum.CUST_TYPE_1.getCustTypeCode().equals(consumer.getCustTypeCode())) {
                            orderCustType = Constants.ORDER_CUST_TYPE_PERSONAL;
                        }
                    }
                    insertWorkOrderHistory(historyRequest.getSubsCode(), spId, pkid, orderNo, orderCustType);

                } catch (Exception e) {
                    log.info("equipmentActivateStatus-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("equipmentActivateStatus-error:{}", e);
        }

    }


    /**
     * 调用1022接口,获取该诉求PKid
     *
     * @param subsCode
     * @param id
     * @return
     */
    private String queryAlarmAppliance(String subsCode, Integer id) {
        String spId = ApplicationUtils.getWorkingSpId();

        String pkidNew = getPkid(subsCode, spId);
        if (StringUtils.isEmpty(pkidNew)) {
            throw new BizException("未获取到pkid");
        }
        //更新诉求pkid
        AppealHistory appealHistory1 = new AppealHistory();
        appealHistory1.setId(id);
        appealHistory1.setPkid(pkidNew);
        appealHistoryMapper.updateById(appealHistory1);
        return pkidNew;
    }

    private String getPkid(String subsCode, String spId) {
        // 查询所有 没有受理的诉求, 进行操作
//        ** 必要条件: 只要3016接口不成功,就不允许继续5016发起诉求
        String param = subsCode;
        log.info(" 调用 1022 报警器信息记录查询");
        Map<String, Object> alarmApplianceMap = tcisService.tcisRequest(null, 3, param,subsCode);
        Integer code2 = (Integer) alarmApplianceMap.get("code");
        if (!code2.equals(0)) throw new BizException("1022 报警器信息记录查询调用失败");
        JSONArray alarmList = JSONArray.parseArray(JSON.toJSONString(alarmApplianceMap.get("data")));
        String pkidNew = "";
        log.info(JSONObject.toJSONString(alarmList));
//        查询该客户的所有pkid, 与返回的pkid进行比较, 不存在表中的,即为本次新pkid
        //不允许 同一个销售单id发起多个安装单;
        QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WorkOrderHistory::getSubsCode, subsCode)
                .eq(WorkOrderHistory::getSpId, spId)
                .eq(WorkOrderHistory::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<WorkOrderHistory> histories = workOrderHistoryService.list(queryWrapper);
        List<String> pkidList = histories.stream().map(WorkOrderHistory::getPkid).collect(Collectors.toList());

        for (int i = 0; i < alarmList.size(); i++) {
            JSONObject alarm = alarmList.getJSONObject(i);
            //资产id为空,则获取pkid,结束循环
            if (StringUtils.isEmpty(alarm.getString("resid"))) {
                String pkid = alarm.getString("pkid");
                if (!pkidList.contains(pkid)) {
                    pkidNew = pkid;
                    log.info("本次安装pkid为 {}", pkidNew);
                    break;
                }
            }
        }
        return pkidNew;
    }


    /**
     * 调用3012接口,受理诉求, 发起安装
     *
     * @param request
     * @param orgCode
     * @param pkid
     * @return
     */
    private String outhouseInstall(InitiateWorkOrderRequest request, String orgCode, String pkid) {
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                .filter(d -> d.getValue().equals(request.getEquipmentType()))
                .collect(Collectors.toList()).get(0);
        String bookTime = DateUtil.format(request.getAppointmentTime(), "yyyy-MM-dd");
        OuthouseInstallRequest installRequest = new OuthouseInstallRequest();
        installRequest.setUserid(request.getSubsCode());
        installRequest.setBusitype(MbpConst.BUSITYPE);
        installRequest.setChnltype(MbpConst.CHNLTYPE);
        installRequest.setBooktime(bookTime);
        installRequest.setContact(request.getContact());
        installRequest.setMobile(request.getTelephone());
        installRequest.setRemark(equipmentTypeDTO.getName() + "+安装");
        installRequest.setOrg(request.getOrgCode());
        //对测试环境进行判断
        if (mbpTestEnv.equals("true")) {
            if (orgCode.equals("1_TA01")) installRequest.setOrg("TA01");
        }

        List<PkidRequest> rests = new ArrayList<>();
        PkidRequest pkidRequest = new PkidRequest();
        pkidRequest.setPkid(pkid);
        rests.add(pkidRequest);
        installRequest.setRests(rests);
        Map<String, Object> installRequestMap = new HashMap<>();
        installRequestMap.put("body", installRequest);
        log.info(" 调用 3012 外购燃气具安装");
        Map<String, Object> installResponseMap = tcisService.tcisRequest(installRequestMap, 1, null,request.getSubsCode());
        Integer code3 = (Integer) installResponseMap.get("code");
        if (!code3.equals(0)) throw new BizException("3012 外购燃气具安装调用失败");
        //data内容为body的内容
        JSONObject data = JSON.parseObject(JSON.toJSONString(installResponseMap.get("data")));
        return data.getString("pkid");
    }


    /**
     * 新增工单历史
     *
     * @param subsCode
     * @param spId
     */
    private void insertWorkOrderHistory(String subsCode, String spId, String pkid, String orderNo, Integer orderCustType) {
        //新增 t_gas_workorder_history
        log.info("新增安装工单:{}", orderNo);
        String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
        WorkOrderHistory history = new WorkOrderHistory();
        history.setWoSeq(woSeq);
        history.setOrderNo(orderNo);
        history.setOrderType(1);
        history.setPkid(pkid);
        history.setSubsCode(subsCode);
        history.setFromSystem(0);  //报警器
        history.setWorkSystem(1); // tcis
        history.setHandleStatus(0); // 进行中
        history.setSpId(spId);
        if (null != orderCustType) {
            history.setCustType(orderCustType);
        }
        workOrderHistoryService.save(history);
    }

    /**
     * 批量查询mbp的工单详情接口
     *
     * @param orderNos
     * @return
     */
    private List<MbpOrderListResponse> getOrderList(List<String> orderNos) {
        List<MbpOrderListResponse> orderList = new ArrayList<>();
        for (String orderNo : orderNos) {
          WorkOrderHistory workOrderHistory=  workOrderHistoryService.selectByOrderNo(orderNo);
            try {
                Map<String, Object> jsonData = new HashMap<>();
                jsonData.put("workpkid", orderNo);
                jsonData.put("pageno", 1);
                jsonData.put("pagesize", 20);
                Map<String, Object> resultMap = tcisService.tcisRequest(jsonData, 4, null,workOrderHistory.getSubsCode());
                log.info("查询mbp工单详情接口,返回：{}", resultMap.toString());
                if (0 == Integer.parseInt(resultMap.get("code") + "")) {
                    Object data = resultMap.get("data");
                    if (data == null) continue;
                    JSONArray objects = JSONObject.parseArray(data + "");
                    JSONObject jsonObject = objects.getJSONObject(0);
                    MbpOrderListResponse res = new MbpOrderListResponse();
                    res.setBizCode(jsonObject.get("busitype").toString());//业务类型
                    res.setOrderNo(jsonObject.get("workpkid").toString());//工单编号
                    res.setCompletedTime(jsonObject.get("finishtime").toString());//完成时间
                    res.setCreateTime(jsonObject.get("createtime").toString());//建单时间
                    res.setOrderStatus(jsonObject.get("state").toString());//工单状态
                    res.setServicerName(jsonObject.get("empname").toString());//处理人
                    res.setCompleteResultStr(jsonObject.get("finishremark").toString());//完成备注
                    res.setBooktime(jsonObject.get("booktime") + "");
                    orderList.add(res);
                }
            } catch (Exception e) {
                log.error("查询mbp工单详情接口异常，orderNo" + orderNo, e);
            }

        }
        return orderList;
    }

    /**
     * 诉求历史
     *
     * @param request
     * @return
     */
    public PageUtil<AppealHistoryResponse> appealHistory(AppealHistoryRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        QueryWrapper<AppealHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(request.getInitiateStartTime() != null, AppealHistory::getCreatedAt, request.getInitiateStartTime(), request.getInitiateEndTime())
                .eq(StringUtil.isNotEmpty(request.getSubsCode()), AppealHistory::getSubsCode, request.getSubsCode())
                .eq(StringUtil.isNotEmpty(request.getStatus()), AppealHistory::getStatus, request.getStatus())
                .eq(StringUtil.isNotEmpty(request.getOrderNo()), AppealHistory::getOrderNo, request.getOrderNo())
                .eq(AppealHistory::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(AppealHistory::getSpId, spId)
                .orderByDesc(AppealHistory::getCreatedAt);

        Page<AppealHistory> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<AppealHistory> historyList = appealHistoryMapper.selectList(queryWrapper);
        List<AppealHistoryResponse> appealHistoryResponses = BeanConvertUtils.convertListTo(historyList, AppealHistoryResponse::new);
        PageUtil<AppealHistoryResponse> pageUtil = new PageUtil<>();
        List<DictionaryItemRespDTO> equipmentTypeDTO = holder.getDictionaryByKey(Constants.EQUIPMENT_TYPE_CODE);
        for (AppealHistoryResponse history : appealHistoryResponses) {
            switch (history.getStatus()) {
                case 0:
                    history.setStatusStr("进行中");
                    break;
                case 1:
                    history.setStatusStr("发起成功");
                    break;
                case 2:
                    history.setStatusStr("发起失败 ");
                    break;
            }

            JSONObject json = JSONObject.parseObject(history.getAppealContent());
            String equipmentType = json.getString("equipmentType");
            String appointmentTime = json.getString("appointmentTime");
            Date date = new Date(Long.parseLong(appointmentTime));
            DictionaryItemRespDTO dto = equipmentTypeDTO.stream().filter(a -> a.getValue().equals(
                    equipmentType)).collect(Collectors.toList()).get(0);
            json.put("equipmentType", dto.getName());
            json.put("appointmentTime", DateUtil.formatDate(date));
            history.setAppealContent(json.toJSONString());
        }
        pageUtil.setList(appealHistoryResponses);
        pageUtil.setTotal(page.getTotal());
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        return pageUtil;
    }

    /**
     * mbp 预约服务
     *
     * @param params
     */
    public Long create(MbpOrderCreateRequest params) {
        log.info("create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            int count = workOrderHistoryService.queryCountByImeis(imei, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            //查看安装工单是否有pkId
            WorkOrderHistory workOrderHistory = workOrderHistoryService.selectPkidByImei(imei, spId, 0, 0);
            LambdaQueryWrapper<WorkOrderHistory> queryNew = new LambdaQueryWrapper<>();
            queryNew.or().eq(WorkOrderHistory::getIsDeleted,0)
                    .eq(WorkOrderHistory::getNewDeviceId,imei)
                    .orderByDesc(WorkOrderHistory::getCreatedAt);
            List<WorkOrderHistory> newImeis = workOrderHistoryMapper.selectList(queryNew);
            log.info("create-newImeis:{}",JSONObject.toJSON(newImeis));
            if ((workOrderHistory == null&&!CollectionUtils.isEmpty(newImeis))||
                    (workOrderHistory != null&&!CollectionUtils.isEmpty(newImeis)
                            &&newImeis.get(0).getCreatedAt().getTime()>workOrderHistory.getCreatedAt().getTime())){
                workOrderHistory = newImeis.get(0);
                log.info("create-workOrderHistory:{}",JSONObject.toJSONString(workOrderHistory));
            }
            if (workOrderHistory==null)workOrderHistory = new WorkOrderHistory();
            log.info("create-workOrderHistory:{}", JSONObject.toJSONString(workOrderHistory));
            if ( StringUtils.isEmpty(workOrderHistory.getPkid())){
                //外购流程，流程三
                InitiateWorkOrderRequest initiateWorkOrderRequest = new InitiateWorkOrderRequest();
                initiateWorkOrderRequest.setSubsCode(params.getSubsCode());
                initiateWorkOrderRequest.setIsbuy("0");
                initiateWorkOrderRequest.setBuyaddr("0");
                String pkid = getPkid(initiateWorkOrderRequest, spId);
                workOrderHistory.setPkid(pkid);
                workOrderHistory.setSubsCode(params.getSubsCode());
                workOrderHistory.setSpId(spId);
                workOrderHistory.setDeviceId(params.getImei());
                log.info("场景三获取pkid:{}",pkid);

            }
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            if (params.getIsSmartKitchen()){
                ConsoleSkRecordsRequest skRecordsRequest = new ConsoleSkRecordsRequest();
                skRecordsRequest.setPage(1);
                skRecordsRequest.setPageSize(1);
                skRecordsRequest.setId(params.getId());
                skRecordsRequest.setDeviceId(params.getImei());
                skRecordsRequest.setDealStatus("0");
                skRecordsRequest.setSpId(spId);
                CommonResponse<ConsoleSkRecordsData> skResp =  consoleSkAlarmService.alarmRecords(skRecordsRequest);
                if( Objects.isNull(skResp) || null == skResp.getData() || null == skResp.getData().getList() ||
                        skResp.getData().getList().size() == 0){
                    throw new BizException("未找到该SOS报警记录或该记录已被处理");
                }
                ConsoleSkRecordsList skData = skResp.getData().getList().get(0);
                state.setConcentration(skData.getAlarmCount());
                params.setAlarmTime(skData.getAlarmTime());
            } else {
                if (!StringUtils.isEmpty(params.getId())&&params.getBizType()==2){
                    HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                    log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                    if (historyAlarm!=null){
                        state.setConcentration(historyAlarm.getConcentration());
                        QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                        templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                .eq(WarningAlarm::getAlarmHistoryId, historyAlarm.getId())
                                .eq(WarningAlarm::getIMEI, params.getImei())
                                .eq(WarningAlarm::getIsDeleted, 0);
                        WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                        if (warningAlarm != null) {
                            params.setAlarmTime(warningAlarm.getWarningStartTime());
                        }
                    }
                }
            }

            Map<String, Object> param = new HashMap<>();
            Map<String, Object> body = new HashMap<>();
            body.put("userid", StringUtils.isEmpty(params.getSubsCode()) ? workOrderHistory.getSubsCode():params.getSubsCode());
            body.put("busitype", MbpConst.BUSIREPAIR);
            body.put("chnltype", MbpConst.CHNLTYPE);
            body.put("booktime", params.getBookDate());
            body.put("contact", params.getName() == null ? params.getCustName(): params.getName());
            body.put("tel", params.getPhone());
            body.put("mobile", params.getPhone());
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if (params.getBizType() == 3) {
                String info = StringUtils.isEmpty(state.getDeviceStatusInfo()) ? "" : state.getDeviceStatusInfo();
                HistoryBroken historyBroken = historyBrokenMapper.selectById(params.getId());
                Date created = new Date();
                if (historyBroken != null && historyBroken.getCreatedAt() != null) {
                    created = historyBroken.getCreatedAt();
                }
                body.put("remark",params.getImei()+ "故障信息（" + DateUtil.format(created, "yyyy-MM-dd HH:mm:ss") + "+" + info + "）" + remark);
            } else if (params.getBizType() == 2 ) {
                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                body.put("remark", params.getImei()+"报警信息（" + params.getAlarmTime() + "+" + lel + "）" + remark);
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    Date start=DateUtil.parse(params.getAlarmTime(),"yyyy-MM-dd HH:mm:ss");
                    Date end=new Date();
                    if (!StringUtils.isEmpty(params.getAlarmEndTime())){
                        end=DateUtil.parse(params.getAlarmEndTime(),"yyyy-MM-dd HH:mm:ss");
                    }
                    event = "报警持续时长：" + getDurationDate(start, end);
                }
                body.put("remark", DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            body.put("org",params.getOrgCode());
            String pkid = workOrderHistory.getPkid();
            Map<String, String> rests = new HashMap<String, String>() {{
                put("pkid",pkid );
            }};
            body.put("rests", new ArrayList<Map<String, String>>() {{
                add(rests);
            }});
            param.put("body", body);
            Map<String, Object> map = new HashMap<>();
            if (params.getIsSmartKitchen()){
                 map = tcisService.tcisRequestSmartKitchen(param, 2,  params.getOrgCode(),params.getJvOrgCode());
            }else {
                map = tcisService.tcisRequest(param, 2, params.getOrgCode(), params.getSubsCode());
            }
            log.info("create-map:{}", JSONObject.toJSONString(map));
            if (0 == Integer.parseInt(map.get("code") + "")) {
                Object data = map.get("data");
                if (data != null) {
                    workOrderHistory.setOrderNo(JSONObject.parseObject(data + "")
                            .getString("pkid"));
                }
            } else {
                throw new BizException(map.get("msg")+"");
            }
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            workOrderHistory.setWoSeq(workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId());
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(1);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            workOrderHistory.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
            workOrderHistoryService.save(workOrderHistory);
            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * mbp 预约服务
     *
     * @param params
     */
    public Long createAppeal(MbpOrderCreateRequest params) {
        log.info("create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            int count = workOrderHistoryService.queryCountByImeis(imei, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            //查看安装工单是否有pkId
            WorkOrderHistory workOrderHistory = workOrderHistoryService.selectPkidByImei(imei, spId, 0, 0);
            LambdaQueryWrapper<WorkOrderHistory> queryNew = new LambdaQueryWrapper<>();
            queryNew.or().eq(WorkOrderHistory::getIsDeleted,0)
                    .eq(WorkOrderHistory::getNewDeviceId,imei)
                    .orderByDesc(WorkOrderHistory::getCreatedAt);
            List<WorkOrderHistory> newImeis = workOrderHistoryMapper.selectList(queryNew);
            log.info("create-newImeis:{}",JSONObject.toJSON(newImeis));
            if ((workOrderHistory == null&&!CollectionUtils.isEmpty(newImeis))||
                    (workOrderHistory != null&&!CollectionUtils.isEmpty(newImeis)
                            &&newImeis.get(0).getCreatedAt().getTime()>workOrderHistory.getCreatedAt().getTime())){
                workOrderHistory = newImeis.get(0);
                log.info("create-workOrderHistory:{}",JSONObject.toJSONString(workOrderHistory));
            }
            if (workOrderHistory==null)workOrderHistory = new WorkOrderHistory();
            log.info("create-workOrderHistory:{}", JSONObject.toJSONString(workOrderHistory));
            if ( StringUtils.isEmpty(workOrderHistory.getPkid())){
                //外购流程，流程三
                InitiateWorkOrderRequest initiateWorkOrderRequest = new InitiateWorkOrderRequest();
                initiateWorkOrderRequest.setSubsCode(params.getSubsCode());
                initiateWorkOrderRequest.setIsbuy("0");
                initiateWorkOrderRequest.setBuyaddr("0");
                String pkid = getPkid(initiateWorkOrderRequest, spId);
                workOrderHistory.setPkid(pkid);
                workOrderHistory.setSubsCode(params.getSubsCode());
                workOrderHistory.setSpId(spId);
                workOrderHistory.setDeviceId(params.getImei());
                log.info("场景三获取pkid:{}",pkid);

            }
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            List<HistoryAlarm> historyAlarms = new ArrayList<>();
            if (!CollectionUtils.isEmpty(params.getIds())&&params.getBizType()==2){
                QueryWrapper<HistoryAlarm> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(HistoryAlarm::getSpId, spId)
                        .in(HistoryAlarm::getId, params.getIds())
                        .eq(HistoryAlarm::getIsDeleted, 0)
                        .orderByDesc(HistoryAlarm::getCreatedAt);
                historyAlarms = historyAlarmMapper.selectList(queryWrapper);
                log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarms));
                if (historyAlarms!=null){
                    state.setConcentration(historyAlarms.get(0).getConcentration());
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .eq(WarningAlarm::getAlarmHistoryId, historyAlarms.get(0).getId())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                    if (warningAlarm != null) {
                        params.setAlarmTime(warningAlarm.getWarningStartTime());
                    }
                }
            }

            Map<String, Object> param = new HashMap<>();
            Map<String, Object> body = new HashMap<>();
            body.put("userid", StringUtils.isEmpty(params.getSubsCode()) ? workOrderHistory.getSubsCode():params.getSubsCode());
            body.put("busitype", MbpConst.BUSIREPAIR);
            body.put("chnltype", MbpConst.CHNLTYPE);
            body.put("booktime", params.getBookDate());
            body.put("contact", params.getName() == null ? params.getCustName(): params.getName());
            body.put("tel", params.getPhone());
            body.put("mobile", params.getPhone());
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if (params.getBizType() == 3) {
                QueryWrapper<HistoryBroken> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(HistoryBroken::getSpId, spId)
                        .in(HistoryBroken::getId, params.getIds())
                        .eq(HistoryBroken::getIsDeleted, 0)
                        .orderByDesc(HistoryBroken::getCreatedAt);
                List<HistoryBroken> historyBrokens = historyBrokenMapper.selectList(queryWrapper);
                if (CollectionUtils.isEmpty(historyBrokens)) {
                    body.put("remark", params.getImei() + "故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "）" + remark);
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append(params.getImei()).append("故障信息（");
                    for (HistoryBroken historyBroken : historyBrokens) {
                        String reason = "";
                        if (StringUtils.isEmpty(historyBroken.getReason())) {
                            reason = historyBroken.getReason();
                        } else {
                            reason = historyBroken.getValveBrokenInfo();
                        }
                        sb.append(historyBroken.getCreatedAt() !=null?DateUtil.format(historyBroken.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"): DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append(",");
                    }
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                }
            } else if (params.getBizType() == 2 ) {
                if (CollectionUtils.isEmpty(historyAlarms)) {
                    String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                    body.put("remark", params.getImei()+"报警信息（" + params.getAlarmTime() + "+" + lel + "）" + remark);
                } else {
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .in(WarningAlarm::getAlarmHistoryId, params.getIds())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(templateQueryWrapper);
                    Map<Long, String> warningAlarmMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(warningAlarms)) {
                        warningAlarmMap = warningAlarms.stream().collect(Collectors.toMap(WarningAlarm::getAlarmHistoryId, WarningAlarm::getWarningStartTime, (a1, a2) -> a1));

                    }
                    StringBuffer sb = new StringBuffer();
                    sb.append(params.getImei()).append("报警信息（");
                    for (HistoryAlarm historyAlarm : historyAlarms) {
                        if (warningAlarmMap.containsKey(historyAlarm.getId())) {
                            sb.append(warningAlarmMap.get(historyAlarm.getId())).append("+");
                        }
                        sb.append(historyAlarm.getConcentration()).append("%LEL,");
                    }
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                }
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    Date start=DateUtil.parse(params.getAlarmTime(),"yyyy-MM-dd HH:mm:ss");
                    Date end=new Date();
                    if (!StringUtils.isEmpty(params.getAlarmEndTime())){
                        end=DateUtil.parse(params.getAlarmEndTime(),"yyyy-MM-dd HH:mm:ss");
                    }
                    event = "报警持续时长：" + getDurationDate(start, end);
                }
                body.put("remark", DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            body.put("org",params.getOrgCode());
            String pkid = workOrderHistory.getPkid();
            Map<String, String> rests = new HashMap<String, String>() {{
                put("pkid",pkid );
            }};
            body.put("rests", new ArrayList<Map<String, String>>() {{
                add(rests);
            }});
            param.put("body", body);
            Map<String, Object> map = new HashMap<>();
            if (params.getIsSmartKitchen()){
                map = tcisService.tcisRequestSmartKitchen(param, 2,  params.getOrgCode(),params.getJvOrgCode());
            }else {
                map = tcisService.tcisRequest(param, 2, params.getOrgCode(), params.getSubsCode());
            }
            log.info("create-map:{}", JSONObject.toJSONString(map));
            if (0 == Integer.parseInt(map.get("code") + "")) {
                Object data = map.get("data");
                if (data != null) {
                    workOrderHistory.setOrderNo(JSONObject.parseObject(data + "")
                            .getString("pkid"));
                }
            } else {
                throw new BizException(map.get("msg")+"");
            }
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            workOrderHistory.setWoSeq(workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId());
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(1);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            workOrderHistory.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
            workOrderHistoryService.save(workOrderHistory);
            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * mbp 预约服务
     *
     * @param params
     */
    public Long createBatch(MbpBatchOrderCreateRequest params) {
        log.info("create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            List<String> imeiList = new ArrayList<>();
            for (HistoryAlarmAndBrokenResponse response : params.getEffectiveData()) {
                if (response.getIMEI().contains("-")) {
                    imeiList.add(response.getIMEI().split("-")[0]);
                } else {
                    imeiList.add(response.getIMEI());
                }
            }
            int count = workOrderHistoryService.queryCountByImeis(imeiList, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            //查看安装工单是否有pkId
            List<WorkOrderHistory> orderHistoryList = workOrderHistoryService.queryPkidByImeis(imeiList, spId, 1, 1);
            log.info("createBatch-workOrderHistory:{}", JSONObject.toJSONString(orderHistoryList));
            WorkOrderHistory workOrderHistory = new WorkOrderHistory();
            if (!CollectionUtils.isEmpty(orderHistoryList)) {
                for (WorkOrderHistory orderHistory : orderHistoryList) {
                    if (!StringUtils.isEmpty(orderHistory.getPkid())) {
                        workOrderHistory = orderHistory;
                        break;
                    }
                }
            }
            LambdaQueryWrapper<WorkOrderHistory> queryNew = new LambdaQueryWrapper<>();
            queryNew.or().eq(WorkOrderHistory::getIsDeleted,0)
                    .eq(WorkOrderHistory::getNewDeviceId,imei)
                    .orderByDesc(WorkOrderHistory::getCreatedAt);
            List<WorkOrderHistory> newImeis = workOrderHistoryMapper.selectList(queryNew);
            log.info("create-newImeis:{}",JSONObject.toJSON(newImeis));
            if ((workOrderHistory == null&&!CollectionUtils.isEmpty(newImeis))||
                    (workOrderHistory != null&&!CollectionUtils.isEmpty(newImeis)
                            &&newImeis.get(0).getCreatedAt().getTime()>workOrderHistory.getCreatedAt().getTime())){
                workOrderHistory = newImeis.get(0);
                log.info("create-workOrderHistory:{}",JSONObject.toJSONString(workOrderHistory));
            }
            if (workOrderHistory==null)workOrderHistory = new WorkOrderHistory();
            log.info("create-workOrderHistory:{}", JSONObject.toJSONString(workOrderHistory));
            if ( StringUtils.isEmpty(workOrderHistory.getPkid())){
                //外购流程，流程三
                InitiateWorkOrderRequest initiateWorkOrderRequest = new InitiateWorkOrderRequest();
                initiateWorkOrderRequest.setSubsCode(params.getSubsCode());
                initiateWorkOrderRequest.setIsbuy("0");
                initiateWorkOrderRequest.setBuyaddr("0");
                String pkid = getPkid(initiateWorkOrderRequest, spId);
                workOrderHistory.setPkid(pkid);
                workOrderHistory.setSubsCode(params.getSubsCode());
                workOrderHistory.setSpId(spId);
                workOrderHistory.setDeviceId(params.getImei());
                log.info("场景三获取pkid:{}",pkid);

            }
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            if (!CollectionUtils.isEmpty(params.getEffectiveData())&&params.getBizType()==2){
                state.setConcentration(params.getEffectiveData().get(0).getConcentration());
            }
            Map<String, Object> param = new HashMap<>();
            Map<String, Object> body = new HashMap<>();
            body.put("userid", StringUtils.isEmpty(params.getSubsCode()) ? workOrderHistory.getSubsCode():params.getSubsCode());
            body.put("busitype", MbpConst.BUSIREPAIR);
            body.put("chnltype", MbpConst.CHNLTYPE);
            body.put("booktime", params.getBookDate());
            body.put("contact", params.getName() == null ? params.getCustName(): params.getName());
            body.put("tel", params.getPhone());
            body.put("mobile", params.getPhone());
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if (params.getBizType() == 3) {
//                String info = StringUtils.isEmpty(state.getDeviceStatusInfo()) ? "" : state.getDeviceStatusInfo();
//                body.put("remark",params.getImei()+ "故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + info + ")" + remark);

                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                    Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                    for (String imeis : listMap.keySet()) {
                        sb.append(imeis).append("故障信息（");
                        for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                            String reason = "";
                            if (StringUtils.isEmpty(brokenResponse.getReason())) {
                                reason = brokenResponse.getReason();
                            } else {
                                reason = brokenResponse.getValveBrokenInfo();
                            }
                            sb.append(DateUtil.format(brokenResponse.getCreatedAt(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append("，");
                        }
                        if (sb.length() > 0) {
                            sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                        }
                        sb.append("）;");
                    }
                }
                if (sb.length() > 0) {
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + remark);
                } else {
                    body.put("remark", remark);
                }
            } else if (params.getBizType() == 2 ) {
//                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
//                body.put("remark", params.getImei()+"报警信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + lel + ")" + remark);

                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                    Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                    List<Long> aralmIds = new ArrayList<>();
                    List<String> imeiLists = new ArrayList<>();
                    for (HistoryAlarmAndBrokenResponse andBrokenResponse : params.getEffectiveData()) {
                        aralmIds.add(andBrokenResponse.getId());
                        imeiLists.add(andBrokenResponse.getIMEI());
                    }
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .in(WarningAlarm::getAlarmHistoryId, aralmIds)
                            .in(WarningAlarm::getIMEI, imeiLists)
                            .eq(WarningAlarm::getIsDeleted, 0)
                            .orderByDesc(WarningAlarm::getCreatedAt);
                    List<WarningAlarm> warningAlarmList = warningAlarmMapper.selectList(templateQueryWrapper);
                    Map<String, WarningAlarm> warningAlarmMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(warningAlarmList)) {
                        //根据设备号+告警记录id确定唯一值
                        warningAlarmMap = warningAlarmList.stream().collect(Collectors.toMap(item -> item.getIMEI() + "_" + item.getAlarmHistoryId(), WarningAlarm -> WarningAlarm, (a1, a2) -> a1));
                    }
                    for (String imeis : listMap.keySet()) {
                        sb.append(imeis).append("报警信息（");
                        for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                            if (warningAlarmMap.containsKey(brokenResponse.getIMEI() + "_" + brokenResponse.getId())) {
                                WarningAlarm warningAlarm = warningAlarmMap.get(brokenResponse.getIMEI() + "_" + brokenResponse.getId());
                                sb.append(warningAlarm.getWarningStartTime()).append("+").append(brokenResponse.getConcentration()).append("%LEL，");
                            }
                        }
                        if (sb.length() > 0) {
                            sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                        }
                        sb.append("）;");
                    }
                }
                if (sb.length() > 0) {
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + remark);
                } else {
                    body.put("remark", remark);
                }
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    Date start=DateUtil.parse(params.getAlarmTime(),"yyyy-MM-dd HH:mm:ss");
                    Date end=new Date();
                    if (!StringUtils.isEmpty(params.getAlarmEndTime())){
                        end=DateUtil.parse(params.getAlarmEndTime(),"yyyy-MM-dd HH:mm:ss");
                    }
                    event = "报警持续时长：" + getDurationDate(start, end);
                }
                body.put("remark", DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            body.put("org",params.getOrgCode());
            String pkid = workOrderHistory.getPkid();
            Map<String, String> rests = new HashMap<String, String>() {{
                put("pkid",pkid );
            }};
            body.put("rests", new ArrayList<Map<String, String>>() {{
                add(rests);
            }});
            param.put("body", body);
            Map<String, Object> map = new HashMap<>();
            if (params.getIsSmartKitchen()){
                map = tcisService.tcisRequestSmartKitchen(param, 2,  params.getOrgCode(),params.getJvOrgCode());
            }else {
                map = tcisService.tcisRequest(param, 2, params.getOrgCode(), params.getSubsCode());
            }
            log.info("create-map:{}", JSONObject.toJSONString(map));
            if (0 == Integer.parseInt(map.get("code") + "")) {
                Object data = map.get("data");
                if (data != null) {
                    workOrderHistory.setOrderNo(JSONObject.parseObject(data + "")
                            .getString("pkid"));
                }
            } else {
                throw new BizException(map.get("msg")+"");
            }
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            workOrderHistory.setWoSeq(workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId());
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(1);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            workOrderHistory.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
            workOrderHistoryService.save(workOrderHistory);
            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 对接新工单服务
     * @param params
     * @return
     */
    public Long createNew(MbpOrderCreateRequest params) {
        if (null == params.getOrderCustType() || !(1 == params.getOrderCustType() || 2 == params.getOrderCustType())) {
            throw new BizException("客户类型必传，且仅能传1,2(1-企业客户 2-个人客户)");
        }
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            if (StringUtils.isEmpty(spId)) {
                spId = params.getSpId();
            }
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            int count = workOrderHistoryService.queryCountByImeis(imei, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)
                state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            if (!StringUtils.isEmpty(params.getId())&&params.getBizType()==2){
                HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                if (historyAlarm!=null){
                    state.setConcentration(historyAlarm.getConcentration());
                }
            }
            ConsoleSkRecordsRequest skRecordsRequest = new ConsoleSkRecordsRequest();
            skRecordsRequest.setPage(1);
            skRecordsRequest.setPageSize(1);
            skRecordsRequest.setId(params.getId());
            skRecordsRequest.setDeviceId(params.getImei());
            skRecordsRequest.setDealStatus("0");
            skRecordsRequest.setSpId(spId);
            CommonResponse<ConsoleSkRecordsData> skResp =  consoleSkAlarmService.alarmRecords(skRecordsRequest);
            if( Objects.isNull(skResp) || null == skResp.getData() || null == skResp.getData().getList() ||
                    skResp.getData().getList().size() == 0){
                throw new BizException("未找到该SOS报警记录或该记录已被处理");
            }
            ConsoleSkRecordsList skData = skResp.getData().getList().get(0);

            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = null;
            try{
                workingUser = ApplicationUtils.getWorkingUser();
            }catch (Exception e){
                log.error("workingUser get error",e);
            }
            OrderCreateRequest orderCreateRequest = new OrderCreateRequest();
            orderCreateRequest.setFromSystem(4);
            orderCreateRequest.setLineBizCode(aqLineBizCde);
            orderCreateRequest.setBizCode(sosBizCode);
            orderCreateRequest.setOutOrderCode(woSeq);
            orderCreateRequest.setBookDate(params.getBookDate());
            orderCreateRequest.setBookTime("08:00-24:00");
            orderCreateRequest.setAssignDept(params.getOrgCode());
            orderCreateRequest.setSubsCode(params.getSubsCode());
            orderCreateRequest.setCustName(params.getCustName());
            orderCreateRequest.setPhone(params.getPhone());
            orderCreateRequest.setSpId(consumerService.getConsumerRelateSpId(params.getConsumerId(),spId));
            orderCreateRequest.setAddress(params.getAddress());
            orderCreateRequest.setCustType(params.getOrderCustType());
            if( !StringUtils.isEmpty(skData.getUserId()) ){
                orderCreateRequest.setMemberId(skData.getUserId());
            }
            if (null==workingUser){
                orderCreateRequest.setCreateName("自动创建");
            }else{
                orderCreateRequest.setCreateName(StringUtils.isEmpty(workingUser.getName()) ? workingUser.getUsername() : workingUser.getName());
            }
            if( !StringUtils.isEmpty(params.getLon()) && !StringUtils.isEmpty(params.getLat()) ){
                orderCreateRequest.setLocation(params.getLon() +"," + params.getLat());
            }
            String deviceTypeName = DeviceType.parse(params.getDeviceType()).getName();
            OrderCreateDeviceList orderCreateDeviceList = new OrderCreateDeviceList();
            orderCreateDeviceList.setDeviceId(params.getImei());
            if( !StringUtils.isEmpty(skData.getDeviceName()) ){
                orderCreateDeviceList.setDeviceName(skData.getDeviceName());
            }else{
                orderCreateDeviceList.setDeviceName(deviceTypeName);
            }
            orderCreateDeviceList.setDeviceTypeName(deviceTypeName);
            orderCreateDeviceList.setInstallPosition(StringUtils.isEmpty(skData.getRoomName())?"-":skData.getRoomName());
            orderCreateDeviceList.setAlarmStartTime(params.getAlarmTime());
            orderCreateDeviceList.setAlarmEndTime(params.getAlarmEndTime());
            List<OrderCreateDeviceList> deviceLists = new ArrayList<>();
            deviceLists.add(orderCreateDeviceList);
            orderCreateRequest.setDeviceList(deviceLists);
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if( StringUtils.isEmpty(remark) ){
                remark = StringUtils.isEmpty(params.getUserRemark()) ? "" : params.getUserRemark();
            }
            if (params.getBizType() == 3) {
                String info = StringUtils.isEmpty(state.getDeviceStatusInfo()) ? "" : state.getDeviceStatusInfo();
                orderCreateRequest.setUserRemark(params.getImei() + "故障信息（" + skData.getAlarmTime() + "+" + info + "）" + remark);
            } else if (params.getBizType() == 2 ) {
                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                orderCreateRequest.setUserRemark(params.getImei() + "报警信息（" + skData.getAlarmTime() + "+" + lel + "）" + remark);
            }else {
                String event;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    Date start=DateUtil.parse(params.getAlarmTime(),"yyyy-MM-dd HH:mm:ss");
                    Date end=new Date();
                    if (!StringUtils.isEmpty(params.getAlarmEndTime())){
                        end=DateUtil.parse(params.getAlarmEndTime(),"yyyy-MM-dd HH:mm:ss");
                    }
                    String durationDate = getDurationDate(start, end);
                    event = "报警持续时长：" + durationDate;
                    orderCreateDeviceList.setAlarmDurationState(durationDate);
                }
                orderCreateRequest.setUserRemark(deviceTypeName + "：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + "，" +remark);
            }

            String orderNo = asstWorkOrderService.createV2(orderCreateRequest);

            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");

            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid("");
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(orderNo);
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            if (null != params.getOrderCustType()) {
                workOrderHistory.setCustType(params.getOrderCustType());
            }
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            if( null!=dtu && null!=dtu.getConsumerId() ) {
                workOrderHistory.setConsumerId(dtu.getConsumerId());
            }
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(2);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            String operateBy = "";
            if (null!=workingUser){
                log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
                operateBy =  StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
                operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            }
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
//            if (params.getSkWorkSystemType() > 0 && null!=params.getUserServiceComboVO()) {
//                skWorkOrderService.createServiceComboOrder(orderNo,
//                        params.getUserServiceComboVO(), skData, params.getIsAuto());
//                if (0 == params.getIsAuto()) {//手动需要转单
//                    //webSocket 给前端的参数
//                    ConsoleSkNotifyAlarmResponse response = new ConsoleSkNotifyAlarmResponse();
//                    BeanUtils.copyProperties(skData, response);
//                    response.setNotifyName(ConsoleSkAlarmTypeEnum.getTypeByCode(skData.getAlarmType()));
//                    response.setNotifyTime(skData.getAlarmTime());
//                    response.setImei(skData.getDeviceId());
//                    response.setInstallationPosition(skData.getRoomName());
//                    response.setEquipmentTypeName(ConsoleSkDeviceTypeEnum.getTypeByCode(skData.getDeviceType()));
//                    response.setPhone(skData.getPhone());
//                    response.setNotifyName("手动转单");
//                    response.setNotifyReason(BrowserNotifyReason.SkOrderAutoGen);
//                    response.setIsPop(true);
//                    response.setIsSystem(true);
//                    response.setMemberId(response.getUserId());
//                    if (!StringUtils.isEmpty(params.getCustName())) {
//                        response.setCustName(params.getCustName());
//                    }
//                    response.setNotifyTime(DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//                    webSocketProcess.redisTopicSendMsg(skData.getSpId(), JSONObject.toJSONString(response));
//                }
//            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 安装对接新工单服务
     * @param params
     * @return
     */
    public Long createNewInstallOrder(InitiateWorkOrderRequest params) {
        if (null == params.getOrderCustType() || !(1 == params.getOrderCustType() || 2 == params.getOrderCustType())) {
            throw new BizException("客户类型必传，且仅能传1,2(1-企业客户 2-个人客户)");
        }
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();

            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            OrderCreateRequest orderCreateRequest = new OrderCreateRequest();
            orderCreateRequest.setFromSystem(4);
            orderCreateRequest.setLineBizCode(aqLineBizCde);
            orderCreateRequest.setBizCode(installBizCode);
            orderCreateRequest.setOutOrderCode(woSeq);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            orderCreateRequest.setBookDate(format.format(params.getAppointmentTime()));
            orderCreateRequest.setBookTime("08:00-24:00");
            orderCreateRequest.setAssignDept(params.getOrgCode());
            orderCreateRequest.setSubsCode(params.getSubsCode());
            orderCreateRequest.setCustName(params.getContact());
            orderCreateRequest.setPhone(params.getTelephone());
            orderCreateRequest.setSpId(consumerService.getConsumerRelateSpId(params.getConsumerId(),spId));
            orderCreateRequest.setAddress(params.getAddress());
            orderCreateRequest.setMemberId(params.getMemberId());
            orderCreateRequest.setCustType(params.getOrderCustType());
            orderCreateRequest.setCreateName(StringUtils.isEmpty(workingUser.getName()) ? workingUser.getUsername() : workingUser.getName());
            if( !StringUtils.isEmpty(params.getLon()) && !StringUtils.isEmpty(params.getLat()) ){
                orderCreateRequest.setLocation(params.getLon() +"," + params.getLat());
            }
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            orderCreateRequest.setUserRemark(remark);
            OrderCreateDeviceList orderCreateDeviceList = new OrderCreateDeviceList();
            orderCreateDeviceList.setSellerNote(params.getBrand());
            //orderCreateDeviceList.setDeviceName(params.getBrand());
            orderCreateDeviceList.setDeviceTypeName(consumerService.dictionaryname(params.getEquipmentType(),"Equipment_type"));
            orderCreateDeviceList.setSupplierName(params.getFactory());
            List<OrderCreateDeviceList> deviceLists = new ArrayList<>();
            deviceLists.add(orderCreateDeviceList);
            orderCreateRequest.setDeviceList(deviceLists);

            String orderNo = asstWorkOrderService.createV2(orderCreateRequest);
            //新增 t_gas_workorder_history
            log.info("时刻家新增安装工单:{}", orderNo);
            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid("");
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(orderNo);
            workOrderHistory.setNewDeviceId("");
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(2);
            workOrderHistory.setOrderType(1);
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            workOrderHistory.setConsumerId(params.getConsumerId());
            log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
            String operateBy = StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
            operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 对接新工单服务
     * @param params
     * @return
     */
    public Long createNewOrderV2(MbpOrderCreateRequest params) {
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)
                state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            if (!StringUtils.isEmpty(params.getId())&&params.getBizType()==2){
                HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                if (historyAlarm!=null){
                    state.setConcentration(historyAlarm.getConcentration());
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .eq(WarningAlarm::getAlarmHistoryId, historyAlarm.getId())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                    if (warningAlarm != null) {
                        params.setAlarmTime(warningAlarm.getWarningStartTime());
                        params.setAlarmDurationTime(warningAlarm.getWarningDuration());
                        if (!StringUtils.isEmpty(warningAlarm.getWarningStartTime()) && !StringUtils.isEmpty(warningAlarm.getWarningDuration())) {
                            String durationDate = getDurationDate(warningAlarm.getWarningStartTime(), warningAlarm.getWarningDuration());
                            params.setAlarmEndTime(durationDate);
                        }
                    }
                }
            }

            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            OrderCreateRequest orderCreateRequest = new OrderCreateRequest();
            orderCreateRequest.setFromSystem(4);
            orderCreateRequest.setLineBizCode(aqLineBizCde);
            if (params.getBizType() == 3) {
                orderCreateRequest.setBizCode(maintainBizCode);
            } else if (params.getBizType() == 2) {
                orderCreateRequest.setBizCode(alarmBizCode);
            } else {
                orderCreateRequest.setBizCode(installBizCode);
            }
            orderCreateRequest.setOutOrderCode(woSeq);
            orderCreateRequest.setBookDate(params.getBookDate());
            orderCreateRequest.setBookTime("08:00-24:00");
            orderCreateRequest.setAssignDept(params.getOrgCode());
            orderCreateRequest.setSubsCode(params.getSubsCode());
            if (StringUtils.isEmpty(params.getCustName())) {
                orderCreateRequest.setCustName(params.getName());
            } else {
                orderCreateRequest.setCustName(params.getCustName());
            }

            orderCreateRequest.setPhone(params.getPhone());
            orderCreateRequest.setSpId(consumerService.getConsumerRelateSpId(params.getConsumerId(),spId));
            orderCreateRequest.setAddress(params.getAddress());
            if (params.getMemberId() != null && params.getMemberId() > 0) {
                orderCreateRequest.setMemberId(String.valueOf(params.getMemberId()));
            }
            orderCreateRequest.setCreateName(StringUtils.isEmpty(workingUser.getName()) ? workingUser.getUsername() : workingUser.getName());
            if( !StringUtils.isEmpty(params.getLon()) && !StringUtils.isEmpty(params.getLat()) ){
                orderCreateRequest.setLocation(params.getLon() +"," + params.getLat());
            }

            OrderCreateDeviceList orderCreateDeviceList = new OrderCreateDeviceList();
            orderCreateDeviceList.setDeviceId(params.getImei());
            if (dtu != null) {
                if( !StringUtils.isEmpty(dtu.getPositionLon()) && !StringUtils.isEmpty(dtu.getPositionLat()) ){
                    orderCreateRequest.setLocation(dtu.getPositionLon() +"," + dtu.getPositionLat());
                }
                orderCreateDeviceList.setSellerNote(dtu.getEquipmentModel());
                orderCreateDeviceList.setDeviceName(dtu.getIMEI() + "-" + dtu.getEquipmentModel());
                DictionaryItemRespDTO dict = holder.getDictionaryByKey(
                        EquipmentType.DICT_CODE, spId).stream().filter(a->a.getValue().equals(
                        dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
                orderCreateDeviceList.setDeviceTypeName(dict.getName());
                orderCreateDeviceList.setInstallPosition(dtu.getInstallationPosition());
                orderCreateDeviceList.setSupplierName(dtu.getEquipmentManufacturer());
            }
            orderCreateDeviceList.setAlarmStartTime(params.getAlarmTime());
            orderCreateDeviceList.setAlarmEndTime(params.getAlarmEndTime());
            orderCreateDeviceList.setAlarmDurationState(params.getAlarmDurationTime());
            List<OrderCreateDeviceList> deviceLists = new ArrayList<>();
            deviceLists.add(orderCreateDeviceList);
            orderCreateRequest.setDeviceList(deviceLists);
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if( StringUtils.isEmpty(remark) ){
                remark = StringUtils.isEmpty(params.getUserRemark()) ? "" : params.getUserRemark();
            }
            if (params.getBizType() == 3) {
                String info = StringUtils.isEmpty(state.getDeviceStatusInfo()) ? "" : state.getDeviceStatusInfo();
                orderCreateRequest.setUserRemark(params.getImei() + "故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + info + "）" + remark);
            } else if (params.getBizType() == 2 ) {
                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                orderCreateRequest.setUserRemark(params.getImei() + "报警信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + lel + "）" + remark);
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    event = "报警持续时长：" + params.getAlarmDurationTime();
                }
                orderCreateRequest.setUserRemark(DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            String orderNo = asstWorkOrderService.createV2(orderCreateRequest);

            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid("");
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(orderNo);
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            if (null != params.getOrderCustType()) {
                workOrderHistory.setCustType(params.getOrderCustType());
            }
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(2);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            if (dtu != null  && null!=dtu.getConsumerId()) {
                workOrderHistory.setConsumerId(dtu.getConsumerId());
            }
            log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
            String operateBy = StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
            operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 批量对接新工单服务
     * @param params
     * @return
     */
    public Long createNewOrderBatch(MbpBatchOrderCreateRequest params) {
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            Consumer consumer = consumerMapper.selectById(params.getConsumerId());
            if (null != consumer && !StringUtils.isEmpty(consumer.getSubsCode())) {
                params.setOrderCustType(workOrderHistoryService.getOrderLaunchCustType(consumer));
            }
            if (null == params.getOrderCustType() ||
                    !(1 == params.getOrderCustType() || 2 == params.getOrderCustType())) {
                throw new BizException("客户类型必传，且仅能传1,2(1-企业客户 2-个人客户)");
            }

            //获取设备对应pkid
//            String imei = params.getImei();
//            if (imei.contains("-")) imei = imei.split("-")[0];
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)
                state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            if (params.getBizType()==2 && !CollectionUtils.isEmpty(params.getEffectiveData())){
                state.setConcentration(params.getEffectiveData().get(0).getConcentration());
                QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                        .eq(WarningAlarm::getAlarmHistoryId, params.getEffectiveData().get(0).getId())
                        .eq(WarningAlarm::getIMEI, params.getImei())
                        .eq(WarningAlarm::getIsDeleted, 0);
                WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                if (warningAlarm != null) {
                    params.setAlarmTime(warningAlarm.getWarningStartTime());
                    params.setAlarmDurationTime(warningAlarm.getWarningDuration());
                    if (!StringUtils.isEmpty(warningAlarm.getWarningStartTime()) && !StringUtils.isEmpty(warningAlarm.getWarningDuration())) {
                        String durationDate = getDurationDate(warningAlarm.getWarningStartTime(), warningAlarm.getWarningDuration());
                        params.setAlarmEndTime(durationDate);
                    }
                }
            }

            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            OrderCreateRequest orderCreateRequest = new OrderCreateRequest();
            orderCreateRequest.setFromSystem(4);
            orderCreateRequest.setLineBizCode(aqLineBizCde);
            if (params.getBizType() == 3) {
                orderCreateRequest.setBizCode(maintainBizCode);
            } else if (params.getBizType() == 2) {
                orderCreateRequest.setBizCode(alarmBizCode);
            } else {
                orderCreateRequest.setBizCode(installBizCode);
            }
            orderCreateRequest.setOutOrderCode(woSeq);
            orderCreateRequest.setBookDate(params.getBookDate());
            orderCreateRequest.setBookTime("08:00-24:00");
            orderCreateRequest.setAssignDept(params.getOrgCode());
            orderCreateRequest.setSubsCode(params.getSubsCode());
            orderCreateRequest.setCustType(params.getOrderCustType());
            if (StringUtils.isEmpty(params.getCustName())) {
                orderCreateRequest.setCustName(params.getName());
            } else {
                orderCreateRequest.setCustName(params.getCustName());
            }

            orderCreateRequest.setPhone(params.getPhone());
            orderCreateRequest.setSpId(consumerService.getConsumerRelateSpId(params.getConsumerId(),spId));
            orderCreateRequest.setAddress(params.getAddress());
            if (params.getMemberId() != null && params.getMemberId() > 0) {
                orderCreateRequest.setMemberId(String.valueOf(params.getMemberId()));
            }
            orderCreateRequest.setCreateName(StringUtils.isEmpty(workingUser.getName()) ? workingUser.getUsername() : workingUser.getName());
            if( !StringUtils.isEmpty(params.getLon()) && !StringUtils.isEmpty(params.getLat()) ){
                orderCreateRequest.setLocation(params.getLon() +"," + params.getLat());
            }

            OrderCreateDeviceList orderCreateDeviceList = new OrderCreateDeviceList();
            orderCreateDeviceList.setDeviceId(params.getImei());
            if (dtu != null) {
                if( !StringUtils.isEmpty(dtu.getPositionLon()) && !StringUtils.isEmpty(dtu.getPositionLat()) ){
                    orderCreateRequest.setLocation(dtu.getPositionLon() +"," + dtu.getPositionLat());
                }
                orderCreateDeviceList.setSellerNote(dtu.getEquipmentModel());
                orderCreateDeviceList.setDeviceName(dtu.getIMEI() + "-" + dtu.getEquipmentModel());
                DictionaryItemRespDTO dict = holder.getDictionaryByKey(
                        EquipmentType.DICT_CODE, spId).stream().filter(a->a.getValue().equals(
                        dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
                orderCreateDeviceList.setDeviceTypeName(dict.getName());
                orderCreateDeviceList.setInstallPosition(dtu.getInstallationPosition());
                orderCreateDeviceList.setSupplierName(dtu.getEquipmentManufacturer());
            }
            orderCreateDeviceList.setAlarmStartTime(params.getAlarmTime());
            orderCreateDeviceList.setAlarmEndTime(params.getAlarmEndTime());
            orderCreateDeviceList.setAlarmDurationState(params.getAlarmDurationTime());
            List<OrderCreateDeviceList> deviceLists = new ArrayList<>();
            deviceLists.add(orderCreateDeviceList);
            orderCreateRequest.setDeviceList(deviceLists);
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if( StringUtils.isEmpty(remark) ){
                remark = StringUtils.isEmpty(params.getUserRemark()) ? "" : params.getUserRemark();
            }
            if (params.getBizType() == 3) {
                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                    Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                    for (String imeis : listMap.keySet()) {
                        sb.append(imeis).append("故障信息（");
                        for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                            String reason = "";
                            if (StringUtils.isEmpty(brokenResponse.getReason())) {
                                reason = brokenResponse.getReason();
                            } else {
                                reason = brokenResponse.getValveBrokenInfo();
                            }
                            sb.append(DateUtil.format(brokenResponse.getCreatedAt(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append("，");
                        }
                        if (sb.length() > 0) {
                            sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                        }
                        sb.append("）;");
                    }
                }
                if (sb.length() > 0) {
                    orderCreateRequest.setUserRemark(sb.toString().substring(0, sb.toString().length() - 1) + remark);
                } else {
                    orderCreateRequest.setUserRemark(remark);
                }
            } else if (params.getBizType() == 2 ) {
                StringBuffer sb = new StringBuffer();
                if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                    Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                    List<Long> aralmIds = new ArrayList<>();
                    List<String> imeiList = new ArrayList<>();
                    for (HistoryAlarmAndBrokenResponse param : params.getEffectiveData()) {
                        aralmIds.add(param.getId());
                        imeiList.add(param.getIMEI());
                    }
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .in(WarningAlarm::getAlarmHistoryId, aralmIds)
                            .in(WarningAlarm::getIMEI, imeiList)
                            .eq(WarningAlarm::getIsDeleted, 0)
                            .orderByDesc(WarningAlarm::getCreatedAt);
                    List<WarningAlarm> warningAlarmList = warningAlarmMapper.selectList(templateQueryWrapper);
                    Map<String, WarningAlarm> warningAlarmMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(warningAlarmList)) {
                        //根据设备号+告警记录id确定唯一值
                        warningAlarmMap = warningAlarmList.stream().collect(Collectors.toMap(item -> item.getIMEI() + "_" + item.getAlarmHistoryId(), WarningAlarm -> WarningAlarm, (a1, a2) -> a1));
                    }
                    for (String imeis : listMap.keySet()) {
                        sb.append(imeis).append("报警信息（");
                        for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                            if (warningAlarmMap.containsKey(brokenResponse.getIMEI() + "_" + brokenResponse.getId())) {
                                WarningAlarm warningAlarm = warningAlarmMap.get(brokenResponse.getIMEI() + "_" + brokenResponse.getId());
                                sb.append(warningAlarm.getWarningStartTime()).append("+").append(brokenResponse.getConcentration()).append("%LEL，");
                            }

                        }
                        if (sb.length() > 0) {
                            sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                        }
                        sb.append("）;");
                    }
                }
                if (sb.length() > 0) {
                    orderCreateRequest.setUserRemark(sb.toString().substring(0, sb.toString().length() - 1) + remark);
                } else {
                    orderCreateRequest.setUserRemark(remark);
                }
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    event = "报警持续时长：" + params.getAlarmDurationTime();
                }
                orderCreateRequest.setUserRemark(DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            String orderNo = asstWorkOrderService.createV2(orderCreateRequest);

            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid("");
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(orderNo);
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(2);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            if (dtu != null  && null!=dtu.getConsumerId()) {
                workOrderHistory.setConsumerId(dtu.getConsumerId());
            }
            log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
            String operateBy = StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
            operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 对接新工单服务
     * @param params
     * @return
     */
    public Long createNewOrder(MbpOrderCreateRequest params) {
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        String spId = ApplicationUtils.getWorkingSpId();
        Consumer consumer = null;
        if (null != params.getConsumerId() && params.getConsumerId() > 0) {
            consumer = consumerMapper.selectById(params.getConsumerId());
        } else if (!StringUtils.isEmpty(params.getSubsCode())){
            consumer = consumerMapper.selectByOrgCode(params.getSubsCode(),spId);
        }
        if (null != consumer && !StringUtils.isEmpty(consumer.getSubsCode())) {
            params.setOrderCustType(workOrderHistoryService.getOrderLaunchCustType(consumer));
        }
        if (null == params.getOrderCustType() || !(1 == params.getOrderCustType() || 2 == params.getOrderCustType())) {
            throw new BizException("客户类型必传，且仅能传1,2(1-企业客户 2-个人客户)");
        }
        try {
            spId = consumerService.getConsumerRelateSpId(params.getConsumerId(), spId);
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            int count = workOrderHistoryService.queryCountByImeis(imei, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)
                state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            List<HistoryAlarm> historyAlarms = new ArrayList<>();
            if (params.getBizType()==2) {
                if (CollectionUtils.isEmpty(params.getIds())) {
                    if (!StringUtils.isEmpty(params.getId())){
                        HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                        log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                        if (historyAlarm!=null){
                            state.setConcentration(historyAlarm.getConcentration());
                            QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                            templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                    .eq(WarningAlarm::getAlarmHistoryId, historyAlarm.getId())
                                    .eq(WarningAlarm::getIMEI, params.getImei())
                                    .eq(WarningAlarm::getIsDeleted, 0);
                            WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                            if (warningAlarm != null) {
                                params.setAlarmTime(warningAlarm.getWarningStartTime());
                                params.setAlarmDurationTime(warningAlarm.getWarningDuration());
                                if (!StringUtils.isEmpty(warningAlarm.getWarningStartTime()) && !StringUtils.isEmpty(warningAlarm.getWarningDuration())) {
                                    String durationDate = getDurationDate(warningAlarm.getWarningStartTime(), warningAlarm.getWarningDuration());
                                    params.setAlarmEndTime(durationDate);
                                }
                            }
                        }
                    }
                } else {
                    QueryWrapper<HistoryAlarm> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(HistoryAlarm::getSpId, spId)
                            .in(HistoryAlarm::getId, params.getIds())
                            .eq(HistoryAlarm::getIsDeleted, 0)
                            .orderByDesc(HistoryAlarm::getCreatedAt);
                    historyAlarms = historyAlarmMapper.selectList(queryWrapper);
                    if (!CollectionUtils.isEmpty(historyAlarms)) {
                        state.setConcentration(historyAlarms.get(0).getConcentration());
                        QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                        templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                .eq(WarningAlarm::getAlarmHistoryId, historyAlarms.get(0).getId())
                                .eq(WarningAlarm::getIMEI, params.getImei())
                                .eq(WarningAlarm::getIsDeleted, 0);
                        WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                        if (warningAlarm != null) {
                            params.setAlarmTime(warningAlarm.getWarningStartTime());
                            params.setAlarmDurationTime(warningAlarm.getWarningDuration());
                            if (!StringUtils.isEmpty(warningAlarm.getWarningStartTime()) && !StringUtils.isEmpty(warningAlarm.getWarningDuration())) {
                                String durationDate = getDurationDate(warningAlarm.getWarningStartTime(), warningAlarm.getWarningDuration());
                                params.setAlarmEndTime(durationDate);
                            }
                        }
                    }
                }
            }


            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            OrderCreateRequest orderCreateRequest = new OrderCreateRequest();
            orderCreateRequest.setFromSystem(4);
            orderCreateRequest.setLineBizCode(aqLineBizCde);
            if (params.getBizType() == 3) {
                orderCreateRequest.setBizCode(maintainBizCode);
            } else if (params.getBizType() == 2) {
                orderCreateRequest.setBizCode(alarmBizCode);
            } else {
                orderCreateRequest.setBizCode(installBizCode);
            }
            orderCreateRequest.setOutOrderCode(woSeq);
            orderCreateRequest.setBookDate(params.getBookDate());
            orderCreateRequest.setBookTime("08:00-24:00");
            orderCreateRequest.setAssignDept(params.getOrgCode());
            orderCreateRequest.setSubsCode(params.getSubsCode());
            orderCreateRequest.setCustType(params.getOrderCustType());
            if (StringUtils.isEmpty(params.getCustName())) {
                orderCreateRequest.setCustName(params.getName());
            } else {
                orderCreateRequest.setCustName(params.getCustName());
            }

            orderCreateRequest.setPhone(params.getPhone());
            orderCreateRequest.setSpId(consumerService.getConsumerRelateSpId(params.getConsumerId(), spId));
            orderCreateRequest.setAddress(params.getAddress());
            if (params.getMemberId() != null && params.getMemberId() > 0) {
                orderCreateRequest.setMemberId(String.valueOf(params.getMemberId()));
            }
            orderCreateRequest.setCreateName(StringUtils.isEmpty(workingUser.getName()) ? workingUser.getUsername() : workingUser.getName());
            if( !StringUtils.isEmpty(params.getLon()) && !StringUtils.isEmpty(params.getLat()) ){
                orderCreateRequest.setLocation(params.getLon() +"," + params.getLat());
            }

            OrderCreateDeviceList orderCreateDeviceList = new OrderCreateDeviceList();
            orderCreateDeviceList.setDeviceId(params.getImei());
            if (dtu != null) {
                if( !StringUtils.isEmpty(dtu.getPositionLon()) && !StringUtils.isEmpty(dtu.getPositionLat()) ){
                    orderCreateRequest.setLocation(dtu.getPositionLon() +"," + dtu.getPositionLat());
                }
                orderCreateDeviceList.setSellerNote(dtu.getEquipmentModel());
                orderCreateDeviceList.setDeviceName(dtu.getIMEI() + "-" + dtu.getEquipmentModel());
                DictionaryItemRespDTO dict = holder.getDictionaryByKey(
                        EquipmentType.DICT_CODE, spId).stream().filter(a->a.getValue().equals(
                        dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
                orderCreateDeviceList.setDeviceTypeName(dict.getName());
                orderCreateDeviceList.setInstallPosition(dtu.getInstallationPosition());
                orderCreateDeviceList.setSupplierName(dtu.getEquipmentManufacturer());
            }
            orderCreateDeviceList.setAlarmStartTime(params.getAlarmTime());
            orderCreateDeviceList.setAlarmEndTime(params.getAlarmEndTime());
            orderCreateDeviceList.setAlarmDurationState(params.getAlarmDurationTime());
            List<OrderCreateDeviceList> deviceLists = new ArrayList<>();
            deviceLists.add(orderCreateDeviceList);
            orderCreateRequest.setDeviceList(deviceLists);
            String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
            if( StringUtils.isEmpty(remark) ){
                remark = StringUtils.isEmpty(params.getUserRemark()) ? "" : params.getUserRemark();
            }
            if (params.getBizType() == 3) {
                //当ids为空时代表是当个处理，不需要拼接
                if (CollectionUtils.isEmpty(params.getIds())) {
                    if (!StringUtils.isEmpty(params.getId())){
                        HistoryBroken historyBroken = historyBrokenMapper.selectById(params.getId());
                        if (null!=historyBroken) {
                            Date created = new Date();
                            if (historyBroken != null && historyBroken.getCreatedAt() != null) {
                                created = historyBroken.getCreatedAt();
                            }
                            String reason = "";
                            if (StringUtils.isEmpty(historyBroken.getReason())) {
                                reason = historyBroken.getReason();
                            } else {
                                reason = historyBroken.getValveBrokenInfo();
                            }
                            orderCreateRequest.setUserRemark(params.getImei() + "故障信息（" + DateUtil.format(created, "yyyy-MM-dd HH:mm:ss") + "+" + reason + "）" + remark);
                        }
                    }
                } else {
                    QueryWrapper<HistoryBroken> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(HistoryBroken::getSpId, spId)
                            .in(HistoryBroken::getId, params.getIds())
                            .eq(HistoryBroken::getIsDeleted, 0)
                            .orderByDesc(HistoryBroken::getCreatedAt);
                    List<HistoryBroken> historyBrokens = historyBrokenMapper.selectList(queryWrapper);
                    if (CollectionUtils.isEmpty(historyBrokens)) {
                        orderCreateRequest.setUserRemark(params.getImei() + "故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "）" + remark);
                    } else {
                        StringBuffer sb = new StringBuffer();
                        sb.append(params.getImei()).append("故障信息（");
                        for (HistoryBroken historyBroken : historyBrokens) {
                            String reason = "";
                            if (StringUtils.isEmpty(historyBroken.getReason())) {
                                reason = historyBroken.getReason();
                            } else {
                                reason = historyBroken.getValveBrokenInfo();
                            }
                            sb.append(historyBroken.getCreatedAt() !=null?DateUtil.format(historyBroken.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"): DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append(",");
                        }
                        orderCreateRequest.setUserRemark(sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                    }
                }

            } else if (params.getBizType() == 2 ) {
                String alarmRemarkStr = "";
                if (!StringUtils.isEmpty(params.getAlarmTime())) {
                    alarmRemarkStr = params.getAlarmTime() + "+";
                }
                //当ids为空时代表是当个处理，不需要拼接
                if (CollectionUtils.isEmpty(params.getIds())) {
                    String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                    orderCreateRequest.setUserRemark(params.getImei() + "报警信息（" + alarmRemarkStr + lel + "）" + remark);
                } else {
                    if (CollectionUtils.isEmpty(historyAlarms)) {
                        String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                        orderCreateRequest.setUserRemark(params.getImei() + "报警信息（" + alarmRemarkStr + lel + "）" + remark);
                    } else {
                        QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                        templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                .in(WarningAlarm::getAlarmHistoryId, params.getIds())
                                .eq(WarningAlarm::getIMEI, params.getImei())
                                .eq(WarningAlarm::getIsDeleted, 0);
                        List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(templateQueryWrapper);
                        Map<Long, String> warningAlarmMap = new HashMap<>();
                        if (!CollectionUtils.isEmpty(warningAlarms)) {
                            warningAlarmMap = warningAlarms.stream().collect(Collectors.toMap(WarningAlarm::getAlarmHistoryId, WarningAlarm::getWarningStartTime, (a1, a2) -> a1));

                        }
                        StringBuffer sb = new StringBuffer();
                        sb.append(params.getImei()).append("报警信息（");
                        for (HistoryAlarm historyAlarm : historyAlarms) {
                            if (warningAlarmMap.containsKey(historyAlarm.getId())) {
                                sb.append(warningAlarmMap.get(historyAlarm.getId())).append("+");
                            }
                            sb.append(historyAlarm.getConcentration()).append("%LEL,");
                        }
                        orderCreateRequest.setUserRemark(sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                    }
                }
            }else {
                String event = null;
                if (params.getDeviceType()==1){
                    event="30min按键"+params.getAlarmCount()+"次";
                }else if (params.getDeviceType()==4){
                    event = "防拆报警/密码错误连续5次";
                }else{
                    event = "报警持续时长：" + params.getAlarmDurationTime();
                }
                orderCreateRequest.setUserRemark(DeviceType.parse(params.getDeviceType()).getName()+"：报警开始时间："
                        + params.getAlarmTime()+ "，" + event + remark);
            }

            String orderNo = asstWorkOrderService.createV2(orderCreateRequest);

            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid("");
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(orderNo);
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(2);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            workOrderHistory.setCustType(params.getOrderCustType());
            if (dtu != null  && null!=dtu.getConsumerId()) {
                workOrderHistory.setConsumerId(dtu.getConsumerId());
            }
            log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
            String operateBy = StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
            operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 对接三商工单接口
     * @param params
     * @return
     */
    public Long createQuotitentOrder(MbpOrderCreateRequest params) {
        log.info("createNew>>create-param:{}",JSONObject.toJSON(params));
        String spId = ApplicationUtils.getWorkingSpId();

        try {
            spId = consumerService.getConsumerRelateSpId(params.getConsumerId(), spId);
            //获取设备对应pkid
            String imei = params.getImei();
            if (imei.contains("-")) imei = imei.split("-")[0];
            int count = workOrderHistoryService.queryCountByImeis(imei, spId);
            if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
            DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
            if (state==null)
                state=new DeviceState();
            log.info("create-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
            List<HistoryAlarm> historyAlarms = new ArrayList<>();
            if (params.getBizType()==2) {
                if (CollectionUtils.isEmpty(params.getIds())) {
                    if (!StringUtils.isEmpty(params.getId())){
                        HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                        log.info("create-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                        if (historyAlarm!=null){
                            state.setConcentration(historyAlarm.getConcentration());
                            QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                            templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                    .eq(WarningAlarm::getAlarmHistoryId, historyAlarm.getId())
                                    .eq(WarningAlarm::getIMEI, params.getImei())
                                    .eq(WarningAlarm::getIsDeleted, 0);
                            WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                            if (warningAlarm != null) {
                                params.setAlarmTime(warningAlarm.getWarningStartTime());
                                params.setAlarmDurationTime(warningAlarm.getWarningDuration());
                                if (!StringUtils.isEmpty(warningAlarm.getWarningStartTime()) && !StringUtils.isEmpty(warningAlarm.getWarningDuration())) {
                                    String durationDate = getDurationDate(warningAlarm.getWarningStartTime(), warningAlarm.getWarningDuration());
                                    params.setAlarmEndTime(durationDate);
                                }
                            }
                        }
                    }
                } else {
                    QueryWrapper<HistoryAlarm> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(HistoryAlarm::getSpId, spId)
                            .in(HistoryAlarm::getId, params.getIds())
                            .eq(HistoryAlarm::getIsDeleted, 0)
                            .orderByDesc(HistoryAlarm::getCreatedAt);
                    historyAlarms = historyAlarmMapper.selectList(queryWrapper);

                }
            }

            Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
            if (!EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())) {
                throw new BizException("该设备不是民用户，不可创建工单");
            }
            Consumer consumer = null;
            if (null != params.getConsumerId() && params.getConsumerId() > 0) {
                consumer = consumerMapper.selectById(params.getConsumerId());
            } else if (!StringUtils.isEmpty(params.getSubsCode())){
                consumer = consumerMapper.selectByOrgCode(params.getSubsCode(),spId);
            }
            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();

            UserBackend workingUser = ApplicationUtils.getWorkingUser();
            ThreeQuotientCreateReq req = new ThreeQuotientCreateReq();
            if (CollectionUtils.isEmpty(params.getIds()) && params.getId()!=null ) {
                req.setFromID(params.getId());
            } else if (!CollectionUtils.isEmpty(params.getIds())) {
                StringBuffer sb = new StringBuffer();
                for (String id : params.getIds()) {
                    sb.append(id).append(",");
                }
                req.setFromID(sb.toString().substring(0, sb.length() -1));
            }else if (!StringUtils.isEmpty(params.getImei())){
                req.setFromID(params.getImei()+"_"+DateUtils.format(new Date(), "yyyyMMddHHmmss"));
            }
            req.setPROP_USERNO(params.getSubsCode());
            if (consumer != null) {
                if (!StringUtils.isEmpty(consumer.getCustName())){
                    req.setName(consumer.getCustName());
                }else {
                    req.setName(consumer.getName());
                }
                req.setCallTel(consumer.getCustPhone());
                req.setLongitude(consumer.getPositionLon());
                req.setLatitude(consumer.getPositionLat());
                String address = "";
                if (!StringUtils.isEmpty(consumer.getCustomerAddress())){
                    address = consumer.getCustomerAddress();
                }else if (!StringUtils.isEmpty(consumer.getCustAddress())){
                    address = consumer.getCustAddress();
                }else if (!StringUtils.isEmpty(consumer.getAddress())){
                    address = consumer.getAddress();
                }
                req.setAddress(address);
            }
            req.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            req.setCallDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            req.setRepairDateTime(params.getBookDate());
            String finalSpId = spId;
            DictionaryItemRespDTO dict = holder.getDictionaryByKey(
                    Constants.THREE_QUOTIENT_COMPANY, spId).stream().filter(a->a.getValue().equals(finalSpId)).collect(Collectors.toList()).get(0);
            if (dict != null) {
                req.setCompanyID(dict.getName());
            }

            req.setRemark(params.getRemark());
            String alarmRemarkStr = "";
            if (!StringUtils.isEmpty(params.getAlarmTime())) {
                alarmRemarkStr = params.getAlarmTime() + "+";
            }
            //当ids为空时代表是当个处理，不需要拼接
            if (CollectionUtils.isEmpty(params.getIds())) {
                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                req.setPROP_MS(params.getImei() + "报警信息（" + alarmRemarkStr + lel + "）");
            } else {
                if (CollectionUtils.isEmpty(historyAlarms)) {
                    String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                    req.setPROP_MS(params.getImei() + "报警信息（" + alarmRemarkStr + lel + "）");
                } else {
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .in(WarningAlarm::getAlarmHistoryId, params.getIds())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(templateQueryWrapper);
                    Map<Long, String> warningAlarmMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(warningAlarms)) {
                        warningAlarmMap = warningAlarms.stream().collect(Collectors.toMap(WarningAlarm::getAlarmHistoryId, WarningAlarm::getWarningStartTime, (a1, a2) -> a1));

                    }
                    StringBuffer sb = new StringBuffer();
                    sb.append(params.getImei()).append("报警信息（");
                    for (HistoryAlarm historyAlarm : historyAlarms) {
                        if (warningAlarmMap.containsKey(historyAlarm.getId())) {
                            sb.append(warningAlarmMap.get(historyAlarm.getId())).append("+");
                        }
                        sb.append(historyAlarm.getConcentration()).append("%LEL,");
                    }
                    req.setPROP_MS(sb.toString().substring(0, sb.toString().length() - 1) + "）");
                }
            }

            ThreeQuotientAddOrderResp addOrderResp = threeQuotientService.addRPSData(req);

            WorkOrderHistory workOrderHistory  = new WorkOrderHistory();
            workOrderHistory.setWoSeq(woSeq);
            workOrderHistory.setPkid(addOrderResp.getSSDH());
            workOrderHistory.setSubsCode(params.getSubsCode());
            workOrderHistory.setOrderNo(addOrderResp.getID());
            workOrderHistory.setDeviceId(params.getImei());
            workOrderHistory.setNewDeviceId("");
            if (state != null) {
                workOrderHistory.setDeviceStatus(state.getDeviceStatus());
                workOrderHistory.setConcentration(state.getConcentration());
            }
            workOrderHistory.setFromSystem(0);
            workOrderHistory.setWorkSystem(4);
            workOrderHistory.setOrderType(params.getBizType());
            workOrderHistory.setHandleStatus(0);
            workOrderHistory.setSpId(spId);
            workOrderHistory.setCustType(params.getOrderCustType());
            if (dtu != null  && null!=dtu.getConsumerId()) {
                workOrderHistory.setConsumerId(dtu.getConsumerId());
            }
            log.info("workingUser:{}",JSONObject.toJSONString(workingUser));
            String operateBy = StringUtils.isEmpty(workingUser.getName()) ? "" : workingUser.getName();
            operateBy += "(" + (StringUtils.isEmpty(workingUser.getUsername()) ? "" : workingUser.getUsername()) + ")";
            workOrderHistory.setOperatorBy(operateBy);
            workOrderHistoryService.save(workOrderHistory);
            if( null!=dtu && null!=dtu.getConsumerId() ){
                Consumer consumerUpdate = new Consumer();
                consumerUpdate.setId(dtu.getConsumerId());
                consumerUpdate.setStatus(1);
                consumerService.updateById(consumerUpdate);
            }
            return workOrderHistory.getId();
        } catch (Exception e) {
            log.error("处理失败",e);
            throw new BizException("预约失败！" + e.getMessage());
        }
    }

    /**
     * 客户导入- 批量发起安装单
     * @param object
     * @param funcAreaMap
     * @return
     */
    public Integer batchInitiateByExcel(List<Object> object,Map<String,FuncArea> funcAreaMap) {
        String spId = ApplicationUtils.getWorkingSpId();
        String nowDate = DateUtil.format(DateUtil.date(), "yyyy-MM-dd"); //当前日期
        String isbuy = String.valueOf(object.get(6)).trim().equals("否") ? "0" : "1";
        String buyaddr = String.valueOf(object.get(7)).trim().equals("公司内部") ? "1" : "2";
        String subsCode = String.valueOf(object.get(0)).trim();
        Integer consumerId = null;
        try {

            ArrayList<GsApplianceRequest> applianceRequests = new ArrayList<>();
            ArrayList<String> imeiList = new ArrayList<>();  //本次安装的imei号集合
            //根据设备数量循环创建入参, 调用5016
            for (int j = 8; j <= 17; j += 2) {
                String IMEI = String.valueOf(object.get(j)).trim();
                imeiList.add(IMEI);
                String installationPosition = String.valueOf(object.get(j + 1)).trim();
                if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                    GsApplianceRequest applianceRequest = new GsApplianceRequest();
                    applianceRequest.setUserid(subsCode);
                    applianceRequest.setAppsource("1"); //报装
                    applianceRequest.setIsuse("1");   // 是
                    applianceRequest.setIsbuy(isbuy);
                    applianceRequest.setRestype("BJ");
                    applianceRequest.setFixposi("1");  //室内
                    applianceRequest.setBuyaddr(buyaddr);
                    applianceRequest.setBuydate(nowDate);
                    applianceRequest.setApplianceid(IMEI);
                    applianceRequests.add(applianceRequest);
                }
            }
            //调用 5016接口
            Map<String, Object> applianceRequestMap = new HashMap<>();
            applianceRequestMap.put("body", applianceRequests);
            log.info("batchInitiateByExcel-调用 5016 工商户用气设备");
            Map<String, Object> applianceResponseMap = tcisService.tcisRequest(applianceRequestMap, 0, null,subsCode);


            Integer code1 = (Integer) applianceResponseMap.get("code");
            //循环调用, 如果此时失败, 记录失败信息
            if (code1.equals(0)) {
                //查询 1022,获取pkid
                String param = subsCode;
                log.info(" 调用 1022 报警器信息记录查询");
                Map<String, Object> alarmApplianceMap = tcisService.tcisRequest(null, 3, param,subsCode);
                Integer code2 = (Integer) alarmApplianceMap.get("code");
                if (!code2.equals(0)) throw new BizException("1022 报警器信息记录查询调用失败");
                JSONArray alarmList = JSONArray.parseArray(JSON.toJSONString(alarmApplianceMap.get("data")));
                log.info(JSONObject.toJSONString(alarmList));


                //遍历设备号,获取设备对应的pkid
                ArrayList<WorkOrderHistory> orderHistories = new ArrayList<>();
                for (String imei : imeiList) {
                    for (int i = 0; i < alarmList.size(); i++) {
                        JSONObject alarm = alarmList.getJSONObject(i);
                        //资产id=imei
                        if (imei.equals(alarm.getString("resid"))) {
                            String pkid = alarm.getString("pkid");
                            log.info("本次设备:{}安装pkid为 {}", imei, pkid);

                            //创建订单信息
                            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
                            WorkOrderHistory history = new WorkOrderHistory();
                            history.setWoSeq(woSeq);
                            history.setOrderNo(woSeq);
                            history.setPkid(pkid);
                            history.setDeviceId(imei);
                            history.setOrderType(Constants.ORDER_TYPE_INSTALL);
                            history.setSubsCode(subsCode);
                            history.setFromSystem(0);  //报警器
                            history.setWorkSystem(1); // tcis
                            history.setHandleStatus(1); // 完成
                            history.setSpId(spId);
                            orderHistories.add(history);
                        }
                    }
                }
                //新增 workOrder 表
                workOrderHistoryService.saveBatch(orderHistories);
            } else {
                throw new BizException("调用5016工商户用气设备失败,户号:" + subsCode);
            }
            //新增用户,建立绑定关系
             consumerId = consumerService.installImportAdd(object, 2, Constants.BIND_CHANNEL_MBP, funcAreaMap);
        } catch (Exception e) {
           throw new BizException("客户:"+ subsCode+",发起安装单失败" + e.getMessage());
        }
        return consumerId;
    }

    public Integer batchInitiateByExcel(List<Object> object,String spId) {
        if (StringUtils.isEmpty(spId)){
            spId = ApplicationUtils.getWorkingSpId();
        }
        String nowDate = DateUtil.format(DateUtil.date(), "yyyy-MM-dd"); //当前日期
        String isbuy = String.valueOf(object.get(3)).equals("否") ? "0" : "1";
        String buyaddr = String.valueOf(object.get(4)).equals("公司内部") ? "1" : "2";
        String subsCode = String.valueOf(object.get(0));
        Integer consumerId = null;
        try {

            ArrayList<GsApplianceRequest> applianceRequests = new ArrayList<>();
            ArrayList<String> imeiList = new ArrayList<>();  //本次安装的imei号集合
            //根据设备数量循环创建入参, 调用5016
            for (int j = 5; j <= 14; j += 2) {

                String IMEI = String.valueOf(object.get(j));
                imeiList.add(IMEI);
                String installationPosition = String.valueOf(object.get(j + 1));
                if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                    GsApplianceRequest applianceRequest = new GsApplianceRequest();
                    applianceRequest.setUserid(subsCode);
                    applianceRequest.setAppsource("1"); //报装
                    applianceRequest.setIsuse("1");   // 是
                    applianceRequest.setIsbuy(isbuy);
                    applianceRequest.setRestype("BJ");
                    applianceRequest.setFixposi("1");  //室内
                    applianceRequest.setBuyaddr(buyaddr);
                    applianceRequest.setBuydate(nowDate);
                    applianceRequest.setApplianceid(IMEI);
                    applianceRequests.add(applianceRequest);
                }
            }
            //调用 5016接口
            Map<String, Object> applianceRequestMap = new HashMap<>();
            applianceRequestMap.put("body", applianceRequests);
            log.info("batchInitiateByExcel-调用 5016 工商户用气设备");
            Map<String, Object> applianceResponseMap = tcisService.tcisRequest(applianceRequestMap, 0, null,subsCode);


            Integer code1 = (Integer) applianceResponseMap.get("code");
            //循环调用, 如果此时失败, 记录失败信息
            if (code1.equals(0)) {
                //查询 1022,获取pkid
                String param = subsCode;
                log.info(" 调用 1022 报警器信息记录查询");
                Map<String, Object> alarmApplianceMap = tcisService.tcisRequest(null, 3, param,subsCode);
                Integer code2 = (Integer) alarmApplianceMap.get("code");
                if (!code2.equals(0)) throw new BizException("1022 报警器信息记录查询调用失败");
                JSONArray alarmList = JSONArray.parseArray(JSON.toJSONString(alarmApplianceMap.get("data")));
                log.info(JSONObject.toJSONString(alarmList));


                //遍历设备号,获取设备对应的pkid
                ArrayList<WorkOrderHistory> orderHistories = new ArrayList<>();
                for (String imei : imeiList) {
                    for (int i = 0; i < alarmList.size(); i++) {
                        JSONObject alarm = alarmList.getJSONObject(i);
                        //资产id=imei
                        if (imei.equals(alarm.getString("resid"))) {
                            String pkid = alarm.getString("pkid");
                            log.info("本次设备:{}安装pkid为 {}", imei, pkid);

                            //创建订单信息
                            String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
                            WorkOrderHistory history = new WorkOrderHistory();
                            history.setWoSeq(woSeq);
                            history.setOrderNo(woSeq);
                            history.setPkid(pkid);
                            history.setDeviceId(imei);
                            history.setOrderType(Constants.ORDER_TYPE_INSTALL);
                            history.setSubsCode(subsCode);
                            history.setFromSystem(0);  //报警器
                            history.setWorkSystem(1); // tcis
                            history.setHandleStatus(1); // 完成
                            history.setSpId(spId);
                            orderHistories.add(history);
                        }
                    }
                }
                //新增 workOrder 表
                workOrderHistoryService.saveBatch(orderHistories);
            } else {
                throw new BizException("调用5016工商户用气设备失败,户号:" + subsCode);
            }
            //新增用户,建立绑定关系
            consumerId = consumerService.installImportAdd(object, 2, Constants.BIND_CHANNEL_MBP,spId);
        } catch (Exception e) {
            throw new BizException("客户:"+ subsCode+",发起安装单失败" + e.getMessage());
        }
        return consumerId;
    }

    public boolean isNotNull(String str) {
        return (!"null".equals(str) && StringUtil.isNotEmpty(str));
    }

    /**
     * 判断客户是否有进行中工单
     *
     * @param consumerId
     */
    public void historyByConsumerId(String consumerId) {
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerService.getOne(queryWrapper);
        if (consumer == null) {
            return;
        }
        String subsCode = consumer.getSubsCode();
        if (StringUtil.isEmpty(subsCode)) return;
        QueryWrapper<WorkOrderHistory> historyQueryWrapper = new QueryWrapper<>();
        historyQueryWrapper.lambda().eq(WorkOrderHistory::getSubsCode, subsCode)
                .eq(WorkOrderHistory::getHandleStatus, Constants.INT_ZERO) //进行中
                .eq(WorkOrderHistory::getSpId, spId)
                .eq(WorkOrderHistory::getIsDeleted, Constants.IS_DELETED_FALSE);

        List<WorkOrderHistory> orderHistories = workOrderHistoryService.list(historyQueryWrapper);
        if (CollectionUtil.isNotEmpty(orderHistories)) {
            throw new BizException("户号: " + subsCode + "存在工单进行中,禁止删除");
        }


    }

    /**
     * mbp 内购预约服务
     *
     * @param params
     */
    public Long createInner(MbpInnerCreateRequest params) {
        log.info("createInner-params:{}", JSONObject.toJSONString(params));
        String spId = ApplicationUtils.getWorkingSpId();
        //获取设备对应pkid
        String imei = params.getImei();
        if (imei.contains("-")) imei = imei.split("-")[0];
        int count = workOrderHistoryService.queryCountByImeis(imei, spId);
        if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
        WorkOrderHistory workOrderHistory = workOrderHistoryService.selectPkidByImei(imei, spId, 1,1);
        log.info("createInner-workOrderHistory:{}", JSONObject.toJSONString(workOrderHistory));
        LambdaQueryWrapper<WorkOrderHistory> queryNew = new LambdaQueryWrapper<>();
        queryNew.or().eq(WorkOrderHistory::getIsDeleted,0)
                .eq(WorkOrderHistory::getNewDeviceId,imei)
                .orderByDesc(WorkOrderHistory::getCreatedAt);
        List<WorkOrderHistory> newImeis = workOrderHistoryMapper.selectList(queryNew);
        log.info("createInner-newImeis:{}",JSONObject.toJSON(newImeis));
        if ((workOrderHistory == null&&!CollectionUtils.isEmpty(newImeis))||
                (workOrderHistory != null&&!CollectionUtils.isEmpty(newImeis)
                        &&newImeis.get(0).getCreatedAt().getTime()>workOrderHistory.getCreatedAt().getTime())){
            workOrderHistory = newImeis.get(0);
            log.info("createInner-workOrderHistory:{}",JSONObject.toJSONString(workOrderHistory));
        }
        DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
        if (state==null)state=new DeviceState();
        log.info("createInner-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
        List<HistoryAlarm> historyAlarms = new ArrayList<>();
        if (params.getBizType()==2) {
            if (CollectionUtils.isEmpty(params.getIds())) {
                if (!StringUtils.isEmpty(params.getId())) {
                    HistoryAlarm historyAlarm = historyAlarmMapper.selectById(params.getId());
                    log.info("createInner-historyAlarm:{}",JSONObject.toJSON(historyAlarm));
                    if (historyAlarm!=null){
                        state.setConcentration(historyAlarm.getConcentration());

                        QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                        templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                                .eq(WarningAlarm::getAlarmHistoryId, historyAlarm.getId())
                                .eq(WarningAlarm::getIMEI, params.getImei())
                                .eq(WarningAlarm::getIsDeleted, 0);
                        WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                        if (warningAlarm != null) {
                            params.setAlarmTime(warningAlarm.getWarningStartTime());
                        }
                    }
                }
            } else {
                QueryWrapper<HistoryAlarm> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(HistoryAlarm::getSpId, spId)
                        .in(HistoryAlarm::getId, params.getIds())
                        .eq(HistoryAlarm::getIsDeleted, 0)
                        .orderByDesc(HistoryAlarm::getCreatedAt);
                historyAlarms = historyAlarmMapper.selectList(queryWrapper);
                if (CollectionUtils.isEmpty(historyAlarms)) {
                    state.setConcentration(historyAlarms.get(0).getConcentration());
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .eq(WarningAlarm::getAlarmHistoryId, historyAlarms.get(0).getId())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    WarningAlarm warningAlarm = warningAlarmMapper.selectOne(templateQueryWrapper);
                    if (warningAlarm != null) {
                        params.setAlarmTime(warningAlarm.getWarningStartTime());
                    }
                }
            }
        }


        Map<String, Object> param = new HashMap<>();
        Map<String, Object> body = new HashMap<>();
        if (workOrderHistory != null) {
            body.put("userid", workOrderHistory.getSubsCode());
        } else {
            body.put("userid", params.getSubsCode());
        }
        body.put("busitype", params.getBizType()==3?MbpConst.BUSIREPAIR_INNER:MbpConst.BUSIALARM_INNER);
        body.put("chnltype", MbpConst.CHNLTYPE);
        body.put("booktime", params.getBookDate());
        body.put("contact", params.getName());
        body.put("tel", params.getPhone());
        body.put("mobile", params.getPhone());
        String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
        if (params.getBizType() == 3) {
            if (CollectionUtils.isEmpty(params.getIds())) {
                HistoryBroken historyBroken = historyBrokenMapper.selectById(params.getId());
                Date created = new Date();
                if (historyBroken != null && historyBroken.getCreatedAt() != null) {
                    created = historyBroken.getCreatedAt();
                }
                String reason = "";
                if (StringUtils.isEmpty(historyBroken.getReason())) {
                    reason = historyBroken.getReason();
                } else {
                    reason = historyBroken.getValveBrokenInfo();
                }
                body.put("remark", params.getImei()+"故障信息（" + DateUtil.format(created, "yyyy-MM-dd HH:mm:ss") + "+" + reason + "）" + remark);
            } else {
                QueryWrapper<HistoryBroken> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(HistoryBroken::getSpId, spId)
                        .in(HistoryBroken::getId, params.getIds())
                        .eq(HistoryBroken::getIsDeleted, 0)
                        .orderByDesc(HistoryBroken::getCreatedAt);
                List<HistoryBroken> historyBrokens = historyBrokenMapper.selectList(queryWrapper);
                if (CollectionUtils.isEmpty(historyBrokens)) {
                    body.put("remark", params.getImei() + "故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "）" + remark);
                } else {
                    StringBuffer sb = new StringBuffer();
                    sb.append(params.getImei()).append("故障信息（");
                    for (HistoryBroken historyBroken : historyBrokens) {
                        String reason = "";
                        if (StringUtils.isEmpty(historyBroken.getReason())) {
                            reason = historyBroken.getReason();
                        } else {
                            reason = historyBroken.getValveBrokenInfo();
                        }
                        sb.append(historyBroken.getCreatedAt() !=null?DateUtil.format(historyBroken.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"): DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append(",");
                    }
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                }
            }

        } else if (params.getBizType() == 2) {
            //当ids为空时代表是当个处理，不需要拼接
            if (CollectionUtils.isEmpty(params.getIds())) {
                String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                body.put("remark", params.getImei()+"报警信息（" + params.getAlarmTime() + "+" + lel + "）" + remark);
            } else {
                if (CollectionUtils.isEmpty(historyAlarms)) {
                    String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
                    body.put("remark", params.getImei()+"报警信息（" + params.getAlarmTime() + "+" + lel + "）" + remark);
                } else {
                    QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                    templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                            .in(WarningAlarm::getAlarmHistoryId, params.getIds())
                            .eq(WarningAlarm::getIMEI, params.getImei())
                            .eq(WarningAlarm::getIsDeleted, 0);
                    List<WarningAlarm> warningAlarms = warningAlarmMapper.selectList(templateQueryWrapper);
                    Map<Long, String> warningAlarmMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(warningAlarms)) {
                        warningAlarmMap = warningAlarms.stream().collect(Collectors.toMap(WarningAlarm::getAlarmHistoryId, WarningAlarm::getWarningStartTime, (a1, a2) -> a1));

                    }
                    StringBuffer sb = new StringBuffer();
                    sb.append(params.getImei()).append("报警信息（");
                    for (HistoryAlarm historyAlarm : historyAlarms) {
                        if (warningAlarmMap.containsKey(historyAlarm.getId())) {
                            sb.append(warningAlarmMap.get(historyAlarm.getId())).append("+");
                        }
                        sb.append(historyAlarm.getConcentration()).append("%LEL,");
                    }
                    body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + "）" + remark);
                }
            }
        }
        body.put("org", params.getOrgCode());
        if (workOrderHistory == null) {
            throw new BizException("错误：[该设备" + imei + "]不存在安装单");
        }
        String pkid = workOrderHistory.getPkid();
        Map<String, String> rests = new HashMap<String, String>() {{
            put("pkid",pkid );
        }};
        body.put("rests", new ArrayList<Map<String, String>>() {{
            add(rests);
        }});
        Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
        body.put("productytpe",dtu!=null?dtu.getEquipmentType():"home_gas_detector");
        body.put("productnum",dtu!=null?dtu.getEquipmentModel():"JT-BJ02Di");
        body.put("alarmcode",params.getImei());
        if (params.getBizType()==2){
            body.put("gasconcentra",StringUtils.isEmpty(state.getConcentration())?"0":state.getConcentration());
        }
        param.put("body", body);
        Map<String, Object> map = tcisService.tcisRequest(param, params.getBizType()==3?5:7, null,workOrderHistory.getSubsCode());
        log.info("createInner-map:{}", JSONObject.toJSONString(map));
        if (0 == Integer.parseInt(map.get("code") + "")) {
            Object data = map.get("data");
            if (data != null) {
                workOrderHistory.setOrderNo(JSONObject.parseObject(data + "")
                        .getString("pkid"));
            }
        } else {
            throw new BizException(map.get("msg")+"");
        }

        if (state != null) {
            workOrderHistory.setDeviceStatus(state.getDeviceStatus());
            workOrderHistory.setConcentration(state.getConcentration());
        }
        workOrderHistory.setDeviceId(params.getImei());
        workOrderHistory.setNewDeviceId("");
        workOrderHistory.setWoSeq(workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId());
        workOrderHistory.setFromSystem(0);
        workOrderHistory.setWorkSystem(1);
        workOrderHistory.setOrderType(params.getBizType());
        workOrderHistory.setHandleStatus(0);
        workOrderHistory.setPkid(workOrderHistory.getPkid());
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        workOrderHistory.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
        workOrderHistory.setCreatedAt(new Date());
        workOrderHistoryService.save(workOrderHistory);
        Consumer consumerUpdate = new Consumer();
        consumerUpdate.setId(dtu.getConsumerId());
        consumerUpdate.setStatus(1);
        consumerService.updateById(consumerUpdate);
        return workOrderHistory.getId();
    }

    /**
     * mbp 内购批量预约服务
     *
     * @param params
     */
    public Long createInnerBatch(MbpBatchOrderCreateRequest params) {
        log.info("createInner-params:{}", JSONObject.toJSONString(params));
        String spId = ApplicationUtils.getWorkingSpId();
        //获取设备对应pkid
        String imei = params.getImei();
        if (imei.contains("-")) imei = imei.split("-")[0];
        List<String> imeiList = new ArrayList<>();
        for (HistoryAlarmAndBrokenResponse response : params.getEffectiveData()) {
            if (response.getIMEI().contains("-")) {
                imeiList.add(response.getIMEI().split("-")[0]);
            } else {
                imeiList.add(response.getIMEI());
            }
        }
        int count = workOrderHistoryService.queryCountByImeis(imeiList, spId);
        if (count > 0) throw new BizException("该设备已存在正在进行的工单，请工单完成后再创建");
        List<WorkOrderHistory> orderHistoryList = workOrderHistoryService.queryPkidByImeis(imeiList, spId, 1, 1);
        log.info("createInner-workOrderHistory:{}", JSONObject.toJSONString(orderHistoryList));
        WorkOrderHistory workOrderHistory = new WorkOrderHistory();
        if (!CollectionUtils.isEmpty(orderHistoryList)) {
            for (WorkOrderHistory orderHistory : orderHistoryList) {
                if (!StringUtils.isEmpty(orderHistory.getPkid())) {
                    workOrderHistory = orderHistory;
                    break;
                }
            }
        }
        LambdaQueryWrapper<WorkOrderHistory> queryNew = new LambdaQueryWrapper<>();
        queryNew.or().eq(WorkOrderHistory::getIsDeleted,0)
                .in(WorkOrderHistory::getNewDeviceId,imeiList)
                .orderByDesc(WorkOrderHistory::getCreatedAt);
        List<WorkOrderHistory> newImeis = workOrderHistoryMapper.selectList(queryNew);
        log.info("createInner-newImeis:{}",JSONObject.toJSON(newImeis));
        if ((workOrderHistory == null&&!CollectionUtils.isEmpty(newImeis))||
                (workOrderHistory != null&&!CollectionUtils.isEmpty(newImeis)
                        &&newImeis.get(0).getCreatedAt().getTime()>workOrderHistory.getCreatedAt().getTime())){
            workOrderHistory = newImeis.get(0);
            log.info("createInner-workOrderHistory:{}",JSONObject.toJSONString(workOrderHistory));
        }
        DeviceState state = deviceStateMapper.selectByDeviceId(params.getImei(), spId);
        if (state==null)state=new DeviceState();
        log.info("createInner-state:{},result:{}",JSONObject.toJSON(state),params.getBizType()==2);
        if (!CollectionUtils.isEmpty(params.getEffectiveData())&&params.getBizType()==2){
            state.setConcentration(params.getEffectiveData().get(0).getConcentration());
        }
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> body = new HashMap<>();
        if (workOrderHistory != null && !StringUtils.isEmpty(workOrderHistory.getSubsCode())) {
            body.put("userid", workOrderHistory.getSubsCode());
        } else {
            body.put("userid", params.getSubsCode());
            workOrderHistory.setSubsCode(params.getSubsCode());
        }
        body.put("busitype", params.getBizType()==3?MbpConst.BUSIREPAIR_INNER:MbpConst.BUSIALARM_INNER);
        body.put("chnltype", MbpConst.CHNLTYPE);
        body.put("booktime", params.getBookDate());
        body.put("contact", params.getName());
        body.put("tel", params.getPhone());
        body.put("mobile", params.getPhone());
        String remark = StringUtils.isEmpty(params.getRemark()) ? "" : params.getRemark();
        if (params.getBizType() == 3) {
//            String info = StringUtils.isEmpty(state.getDeviceStatusInfo()) ? "" : state.getDeviceStatusInfo();
//            body.put("remark", params.getImei()+"故障信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + info + ")" + remark);

            StringBuffer sb = new StringBuffer();
            if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                for (String imeis : listMap.keySet()) {
                    sb.append(imeis).append("故障信息（");
                    for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                        String reason = "";
                        if (StringUtils.isEmpty(brokenResponse.getReason())) {
                            reason = brokenResponse.getReason();
                        } else {
                            reason = brokenResponse.getValveBrokenInfo();
                        }
                        sb.append(DateUtil.format(brokenResponse.getCreatedAt(), "yyyy-MM-dd HH:mm:ss")).append("+").append(reason).append("，");
                    }
                    if (sb.length() > 0) {
                        sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                    }
                    sb.append("）;");
                }
            }
            if (sb.length() > 0) {
                body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + remark);
            } else {
                body.put("remark", remark);
            }
        } else if (params.getBizType() == 2) {
//            String lel = StringUtils.isEmpty(state.getConcentration()) ? "0%LEL" : state.getConcentration() + "%LEL";
//            body.put("remark", params.getImei()+"报警信息（" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "+" + lel + ")" + remark);

            StringBuffer sb = new StringBuffer();
            if (!CollectionUtils.isEmpty(params.getEffectiveData())) {
                Map<String, List<HistoryAlarmAndBrokenResponse>> listMap = params.getEffectiveData().stream().collect(Collectors.groupingBy(HistoryAlarmAndBrokenResponse::getIMEI));
                List<Long> aralmIds = new ArrayList<>();
                List<String> imeiLists = new ArrayList<>();
                for (HistoryAlarmAndBrokenResponse andBrokenResponse : params.getEffectiveData()) {
                    aralmIds.add(andBrokenResponse.getId());
                    imeiLists.add(andBrokenResponse.getIMEI());
                }
                QueryWrapper<WarningAlarm> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.lambda().eq(WarningAlarm::getSpId, spId)
                        .in(WarningAlarm::getAlarmHistoryId, aralmIds)
                        .in(WarningAlarm::getIMEI, imeiLists)
                        .eq(WarningAlarm::getIsDeleted, 0)
                        .orderByDesc(WarningAlarm::getCreatedAt);
                List<WarningAlarm> warningAlarmList = warningAlarmMapper.selectList(templateQueryWrapper);
                Map<String, WarningAlarm> warningAlarmMap = new HashMap<>();
                if (!CollectionUtils.isEmpty(warningAlarmList)) {
                    //根据设备号+告警记录id确定唯一值
                    warningAlarmMap = warningAlarmList.stream().collect(Collectors.toMap(item -> item.getIMEI() + "_" + item.getAlarmHistoryId(), WarningAlarm -> WarningAlarm, (a1, a2) -> a1));
                }
                for (String imeis : listMap.keySet()) {
                    sb.append(imeis).append("报警信息（");
                    for (HistoryAlarmAndBrokenResponse brokenResponse : listMap.get(imeis)) {
                        if (warningAlarmMap.containsKey(brokenResponse.getIMEI() + "_" + brokenResponse.getId())) {
                            WarningAlarm warningAlarm = warningAlarmMap.get(brokenResponse.getIMEI() + "_" + brokenResponse.getId());
                            sb.append(warningAlarm.getWarningStartTime()).append("+").append(brokenResponse.getConcentration()).append("%LEL，");
                        }

                    }
                    if (sb.length() > 0) {
                        sb = new StringBuffer(sb.substring(0, sb.toString().length() - 1));
                    }
                    sb.append("）;");
                }
            }
            if (sb.length() > 0) {
                body.put("remark", sb.toString().substring(0, sb.toString().length() - 1) + remark);
            } else {
                body.put("remark", remark);
            }
        }
        body.put("org", params.getOrgCode());
        if (workOrderHistory == null) {
            throw new BizException("错误：[该设备" + imei + "]不存在安装单");
        }
        String pkid = workOrderHistory.getPkid();
        Map<String, String> rests = new HashMap<String, String>() {{
            put("pkid",pkid );
        }};
        body.put("rests", new ArrayList<Map<String, String>>() {{
            add(rests);
        }});
        Dtu dtu = dtuMapper.selectByImei(params.getImei(), "");
        body.put("productytpe",dtu!=null?dtu.getEquipmentType():"home_gas_detector");
        body.put("productnum",dtu!=null?dtu.getEquipmentModel():"JT-BJ02Di");
        body.put("alarmcode",params.getImei());
        if (params.getBizType()==2){
            body.put("gasconcentra",StringUtils.isEmpty(state.getConcentration())?"0":state.getConcentration());
        }
        param.put("body", body);
        Map<String, Object> map = tcisService.tcisRequest(param, params.getBizType()==3?5:7, null,workOrderHistory.getSubsCode());
        log.info("createInner-map:{}", JSONObject.toJSONString(map));
        if (0 == Integer.parseInt(map.get("code") + "")) {
            Object data = map.get("data");
            if (data != null) {
                workOrderHistory.setOrderNo(JSONObject.parseObject(data + "")
                        .getString("pkid"));
            }
        } else {
            throw new BizException(map.get("msg")+"");
        }

        if (state != null) {
            workOrderHistory.setDeviceStatus(state.getDeviceStatus());
            workOrderHistory.setConcentration(state.getConcentration());
        }
        workOrderHistory.setDeviceId(params.getImei());
        workOrderHistory.setNewDeviceId("");
        workOrderHistory.setWoSeq(workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId());
        workOrderHistory.setFromSystem(0);
        workOrderHistory.setWorkSystem(1);
        workOrderHistory.setOrderType(params.getBizType());
        workOrderHistory.setHandleStatus(0);
        workOrderHistory.setPkid(workOrderHistory.getPkid());
        UserBackend workingUser = ApplicationUtils.getWorkingUser();
        workOrderHistory.setOperatorBy(workingUser.getName() + "(" + workingUser.getUsername() + ")");
        workOrderHistory.setCreatedAt(new Date());
        workOrderHistoryService.save(workOrderHistory);
        Consumer consumerUpdate = new Consumer();
        consumerUpdate.setId(dtu.getConsumerId());
        consumerUpdate.setStatus(1);
        consumerService.updateById(consumerUpdate);
        return workOrderHistory.getId();
    }

    /**
     * mbp 诉求处理部门查询
     */
    public Object orgInfos(OrgInfosRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        String spId = ApplicationUtils.getWorkingSpId();
        QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                .eq(FieldTemplate::getTemplateType, 1)
                .eq(FieldTemplate::getIsDeleted, 0);
        FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
        if (request.getBizType() == 3) {
            resultMap = encapsulationOrg(request, fieldTemplate.getBrokenHandleType(), spId);
        } else if (request.getBizType() == 2) {
            resultMap = encapsulationOrg(request, fieldTemplate.getAlarmHandleType(), spId);
        } else {
            resultMap = encapsulationOrg(request, fieldTemplate.getWorkSystemType(), spId);
        }

        return resultMap;
    }

    //封装处理部门数据
    public Map<String, Object> encapsulationOrg(OrgInfosRequest request, int type, String spId) {
        Map<String, Object> resultMap = new HashMap<>();
        if (type == 2) {
            OrgInfoRequest orgInfoRequest = new OrgInfoRequest();
            orgInfoRequest.setLineBizCode(aqLineBizCde);
            if( request.getIsSmartKitchen() ){
                orgInfoRequest.setBizCode(sosBizCode);
            }else{
                if (request.getBizType() == 3) {
                    orgInfoRequest.setBizCode(maintainBizCode);
                } else if (request.getBizType() == 2) {
                    orgInfoRequest.setBizCode(alarmBizCode);
                } else {
                    orgInfoRequest.setBizCode(installBizCode);
                }
            }
            if (!StringUtils.isEmpty(request.getConsumerId())) {
                spId = consumerService.getConsumerRelateSpId(Integer.parseInt(request.getConsumerId()),spId);
            }
            orgInfoRequest.setSpId(spId);

            List<OrgInfoResponse> orgInfoResponses = asstWorkOrderService.getDeptList(orgInfoRequest);
            List<Map<String,String>> list = new ArrayList<>();
            for (OrgInfoResponse orgInfo:orgInfoResponses) {
                Map<String,String> data = new HashMap<>();
                data.put("orgcode",orgInfo.getOrgCode());
                data.put("orgid",orgInfo.getId());
                data.put("orgname",orgInfo.getOrgName());
                list.add(data);
            }
            resultMap.put("body",list);
        } else {
            String busitype="";
            if (request.getBizType()==1){
                busitype=MbpConst.BUSITYPE;
            }else if (request.getBizType()==2){
                busitype= MbpConst.BUSIALARM_INNER;
            }else if (request.getBizType()==3){
                busitype= MbpConst.BUSIREPAIR_INNER;
            }else {
                busitype= MbpConst.BUSITYPE;
            }
            Map<String, Object> param = new HashMap<>();
            Map<String, Object> body = new HashMap<>();
            body.put("busitype", busitype);
            param.put("body", body);
            Map<String, Object> map = new HashMap<>();
            if (request.getIsSmartKitchen()){
                map = tcisService.tcisRequestSmartKitchen(param, 6, null, request.getJvOrgCode());
            }else {
                map = tcisService.tcisRequest(param, 6, null, request.getConsumerId());
            }
            log.info("orgInfos-map:{}", JSONObject.toJSONString(map));
            if (0 == Integer.parseInt(map.get("code") + "")) {
                Object data = map.get("data");
                if (data != null) {
                    resultMap.put("body",data);
                    return resultMap;
                }
            } else {
                throw new BizException("诉求处理部门查询失败");
            }
            resultMap.put("body",new ArrayList<>());
        }
        return resultMap;
    }

    @Transactional
    public void appealKitchenRecord(MbpOrderCreateRequest req) {
        String spId = ApplicationUtils.getWorkingSpId();
        //已处理
        if (req.getStatus() == 1) {
            log.info("create-智慧厨房设备已处理:{}",JSONObject.toJSONString(req));
            SmartKitchenLog appealLog = new SmartKitchenLog();
            appealLog.setRecordId(req.getId().toString());
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_2);
            appealLog.setAppealResult(req.getAppealResult());
            appealLog.setSpId(spId);
            appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
            appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
            appealLog.setAppealType(0);
            appealLog.setBizType(req.getBizType());
            log.info("新增mbp工单诉求记录：" + appealLog.toString());
            kitchenLogService.save(appealLog);
            ConsoleSkUpdateRequest request = new ConsoleSkUpdateRequest();
            request.setId(req.getId().toString());
            request.setDealStatus(req.getStatus()==1?2:1);
            log.info("alarmSOSUpdate-request:{}",JSONObject.toJSONString(request));
            ConsoleSkUpdateResponse consoleSkUpdateResponse = client.alarmSOSUpdate(request);
            log.info("alarmSOSUpdate-consoleSkUpdateResponse:{}",JSONObject.toJSONString(consoleSkUpdateResponse));
        } else if (req.getStatus() == 2) {
            log.info("create-智慧厨房转工单:{}",JSONObject.toJSONString(req));
            //转工单
            Long workorderId;
            QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                    .eq(FieldTemplate::getTemplateType, 1)
                    .eq(FieldTemplate::getIsDeleted, 0);
            FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
            //int workSystemType = fieldTemplate.getWorkSystemType();
            Integer skWorkSystemType = fieldTemplate.getSkWorkSystemType();
//            if (fieldTemplate.getSkWorkSystemType() > 0) {
//                workSystemType = fieldTemplate.getSkWorkSystemType();
//
//            }
            String appealResult = req.getAppealResult() == null ? "工单处理中": req.getAppealResult();
            if ( skWorkSystemType == 3 ){
                appealResult = "师傅帮个忙工单处理中";
                workorderId = skWorkOrderService.manualCreateOrder(req, spId);
            }else if (skWorkSystemType == 2){
//                if (fieldTemplate.getSkWorkSystemType()>0) {
//                    UserServiceComboVO userServiceComboVO = serviceComboDetailService.getUserServiceCombo(
//                            String.valueOf(req.getDeviceType()), req.getMemberId(), spId);
//                    req.setIsAuto(0);
//                    req.setSkWorkSystemType(fieldTemplate.getSkWorkSystemType());
//                    req.setSpId(spId);
//                    req.setUserServiceComboVO(userServiceComboVO);
//                }
                workorderId = this.createNew(req);
            }else{
                workorderId = this.create(req);
            }
            if (workorderId != null) {
                //同步到智慧厨房
                WorkOrderHistory workOrder = workOrderHistoryService.getById(workorderId);
                ConsoleSkUpdateRequest request = new ConsoleSkUpdateRequest();
                request.setId(req.getId().toString());
                request.setDealStatus(1);
                request.setContact(req.getCustName());
                request.setContactAddress(req.getAddress());
                request.setContactPhone(req.getPhone());
                request.setResult(appealResult);
                request.setWorkOrderNo(workOrder.getOrderNo());
                request.setSubsCode(req.getSubsCode());
                request.setJvOrgCode(req.getJvOrgCode());
                log.info("alarmSOSUpdate- request:{}",JSONObject.toJSONString(request));
                ConsoleSkUpdateResponse consoleSkUpdateResponse = client.alarmSOSUpdate(request);
                log.info("alarmSOSUpdate-consoleSkUpdateResponse:{}",JSONObject.toJSONString(consoleSkUpdateResponse));
                UserBackend userBackend = null;
                try {
                    userBackend = ApplicationUtils.getWorkingUser();
                }catch (Exception e){
                    log.info("userBackend is null");
                }

                SmartKitchenLog appealLog = new SmartKitchenLog();
                appealLog.setWorkorderId(workorderId);
                appealLog.setRecordId(req.getId().toString());
                appealLog.setAppealStatus(Constants.APPEAL_STATUS_1);
                appealLog.setSpId(spId);
                appealLog.setUserName(null==userBackend?"系统":userBackend.getName());
                appealLog.setUserAccount(null==userBackend?"system":userBackend.getUsername());
                appealLog.setAppealResult(req.getAppealResult());
                appealLog.setAppealType(0);
                appealLog.setBizType(req.getBizType());
                appealLog.setRemark(req.getRemark());
                log.info("新增智慧厨房设备诉求记录：" + appealLog.toString());
                kitchenLogService.save(appealLog);
            }
        }

    }

    @Transactional
    public void appealAlarmSystem(MbpOrderCreateRequest req) {
        String spId = ApplicationUtils.getWorkingSpId();
        //已处理
        if (req.getStatus() == 1) {
            AppealLog appealLog = new AppealLog();
            appealLog.setAlarmBrokenId(Long.valueOf(req.getId()));
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_2);
            appealLog.setAppealResult(req.getAppealResult());
            appealLog.setSpId(spId);
            appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
            appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
            if (req.getBizType().equals(2)) {
                appealLog.setAppealType(0);
            } else if (req.getBizType().equals(3)) {
                appealLog.setAppealType(1);
            }
            log.info("新增报警诉求记录："+appealLog.toString());
            appealLogService.save(appealLog);
            // 更新报警/故障信息记录主表
            if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarm = new HistoryAlarm();
                historyAlarm.setValveBrokenInfo(req.getValveBrokenInfo());
                historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                historyAlarm.setAppealResult(appealLog.getAppealResult());
                historyAlarm.setUserName(appealLog.getUserName());
                historyAlarm.setUserAccount(appealLog.getUserAccount());
                historyAlarm.setAppealTime(appealLog.getCreatedAt());
                boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
            } else  if (appealLog.getAppealType() == 1) {
                LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                HistoryBroken historyBroken = new HistoryBroken();
                historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyBroken.setAppealStatus(appealLog.getAppealStatus());
                historyBroken.setAppealResult(appealLog.getAppealResult());
                historyBroken.setUserName(appealLog.getUserName());
                historyBroken.setUserAccount(appealLog.getUserAccount());
                historyBroken.setAppealTime(appealLog.getCreatedAt());
                boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
            }
        } else if (req.getStatus() == 2) {
            //转工单
            Long workorderId = null;
            MbpOrderCreateRequest params = new MbpOrderCreateRequest();
            BeanUtils.copyProperties(req,params);
            QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                    .eq(FieldTemplate::getTemplateType, 1)
                    .eq(FieldTemplate::getIsDeleted, 0);
            FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
            if (req.getBizType() == 2) {
                if (fieldTemplate.getAlarmHandleType() == 3){
                    workorderId = this.createQuotitentOrder(req);
                } else if (fieldTemplate.getAlarmHandleType() == 2){
                    workorderId = this.createNewOrder(req);
                } else {
                    if (isInnerBuy(req.getImei(), spId)) {
                        MbpInnerCreateRequest innerCreateRequest = new MbpInnerCreateRequest();
                        BeanUtils.copyProperties(req,innerCreateRequest);
                        if (null!=req.getId()) {
                            innerCreateRequest.setId(Long.parseLong(req.getId()));
                        }
                        workorderId =  this.createInner(innerCreateRequest);
                    }else {
                        workorderId = this.create(params);
                    }
                }
            } else {
                if (fieldTemplate.getBrokenHandleType() == 2){
                    workorderId = this.createNewOrder(req);
                } else {
                    if (isInnerBuy(req.getImei(), spId)) {
                        MbpInnerCreateRequest innerCreateRequest = new MbpInnerCreateRequest();
                        BeanUtils.copyProperties(req,innerCreateRequest);
                        if (null!=req.getId()) {
                            innerCreateRequest.setId(Long.parseLong(req.getId()));
                        }
                        workorderId =  this.createInner(innerCreateRequest);
                    }else {
                        workorderId = this.create(params);
                    }
                }
            }
            if (workorderId != null && req.getId() != null) {
                AppealLog appealLog = new AppealLog();
                appealLog.setWorkorderId(workorderId);
                appealLog.setAlarmBrokenId(Long.valueOf(req.getId()));
                appealLog.setAppealStatus(Constants.APPEAL_STATUS_1);
                appealLog.setSpId(spId);
                appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                if (req.getBizType().equals(2)) {
                    appealLog.setAppealType(0);
                } else if (req.getBizType().equals(3)) {
                    appealLog.setAppealType(1);
                }
                log.info("新增报警诉求记录："+appealLog.toString());
                appealLogService.save(appealLog);
                // 更新报警/故障信息记录主表
                if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarm = new HistoryAlarm();
                    historyAlarm.setValveBrokenInfo(req.getValveBrokenInfo());
                    historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                    historyAlarm.setAppealResult(appealLog.getAppealResult());
                    historyAlarm.setUserName(appealLog.getUserName());
                    historyAlarm.setUserAccount(appealLog.getUserAccount());
                    historyAlarm.setAppealTime(appealLog.getCreatedAt());
                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                } else if (appealLog.getAppealType() == 1) {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBroken = new HistoryBroken();
                    historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyBroken.setAppealStatus(appealLog.getAppealStatus());
                    historyBroken.setAppealResult(appealLog.getAppealResult());
                    historyBroken.setUserName(appealLog.getUserName());
                    historyBroken.setUserAccount(appealLog.getUserAccount());
                    historyBroken.setAppealTime(appealLog.getCreatedAt());
                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                }
            }
        } else {
            MbpOrderCreateRequest params = new MbpOrderCreateRequest();
            BeanUtils.copyProperties(req,params);
            this.create(params);
        }
    }

    private boolean isInnerBuy(String imei, String spId) {
        log.info("isInnerBuy-imei:{}",imei);
        if(imei.contains("-")){
            imei=imei.split("-")[0];
        }
        log.info("isInnerBuy-imei:{}",imei);
        Dtu one = equipmentService.getDeviceByImei(imei, spId);
        log.info("isInnerBuy-one:{},{}",one,spId );
        if (one != null && one.getSource() == 1){
            return true;
        }
        return false;
    }

    private String getDurationDate(Date startDate, Date endDate) {
        String formatBetween = DateUtil.formatBetween(endDate, startDate, BetweenFormatter.Level.SECOND);
        System.out.println(formatBetween);
        formatBetween = formatBetween.replace(BetweenFormatter.Level.SECOND.getName(), "");
        if (formatBetween.contains(BetweenFormatter.Level.MINUTE.getName())) {
            formatBetween = formatBetween.replace(BetweenFormatter.Level.MINUTE.getName(), split_m);
        } else {
            formatBetween = "00" + split_m + formatBetween;
        }
        if (formatBetween.contains(BetweenFormatter.Level.HOUR.getName())) {
            formatBetween = formatBetween.replace(BetweenFormatter.Level.HOUR.getName(), split_m);
        } else {
            formatBetween = "00" + split_m + formatBetween;
        }
        if (formatBetween.contains(BetweenFormatter.Level.DAY.getName())) {
            formatBetween = formatBetween.substring(formatBetween.indexOf(BetweenFormatter.Level.DAY.getName()), formatBetween.length());
            formatBetween = "59" + formatBetween.substring(formatBetween.indexOf(split_m), formatBetween.length());
        }
        String format = "";
        String[] split = formatBetween.split(split_m);
        for (int i = 0; i < split.length; i++) {
            String s = split[i] + split_m;
            if (s.length() < 3 && s.length() == 2) {
                format = format + "0" + s;
            } else {
                format = format + s;
            }
        }
        if (format.substring(format.length() - 1, format.length()).contains(split_m)) {
            format = format.substring(0, format.length() - 1);
        }
        return format;
    }


    /**
     * 根据开始时间和持续时间算结束时间
     * @param startDate
     * @param durationDate
     * @return
     */
    private String getDurationDate(String startDate, String durationDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.parse(startDate,"yyyy-MM-dd HH:mm:ss"));
        String[] split = durationDate.split(":");
        if (split.length == 3) {
            calendar.add(Calendar.HOUR, Integer.valueOf(split[0]));
            calendar.add(Calendar.MINUTE, Integer.valueOf(split[1]));
            calendar.add(Calendar.SECOND, Integer.valueOf(split[2]));
        } else {
            calendar.add(Calendar.HOUR, Integer.valueOf(split[0]));
            calendar.add(Calendar.MINUTE, Integer.valueOf(split[1]));
        }

        Date time = calendar.getTime();
        String format = DateUtil.format(time, "yyyy-MM-dd HH:mm:ss");
        return format;
    }

}
